1

我正在尝试选择在论坛列表中没有帖子的用户。为此,我写了一个这样的查询

users_id = Post.where(:forum_id => 1).collect { |c| c.user_id }
@users = User.where('topic_id = ? and id not in ? ', "#{@topic.id}", "#{users_id}")

此代码引发 mysql 错误,并在我的日志中

SELECT `user`.* FROM `user` WHERE (forum_id = '2222' and id not in '[5877, 5899, 5828, 5876, 5841, 5838, 5840, 5882, 5881, 5870, 5842, 5843, 5844, 5845, 5889, 5896, 5869, 5847, 5849, 5850, 5855, 5857, 5859, 5867, 5861, 5863, 5865, 5868, 5829, 5830, 5831, 5832, 5833, 5900, 6326, 6326, 6332, 5898, 6333, 6334, 6335, 6336, 6339, 7034, 7019, 6336, 5887, 5827, 9940, 9943, 9949, 7030, 9979, 9980, 5892, 9896, 14208, 14224, 14281, 14282, 14283, 5894, 5895, 14689, 14717]'

在 mysql 中,我执行以下查询,并得到了预期的结果

select * from users where topic_id = 1 and id not in (select users_id from posts where forum_id = 1);

Rails 中的上述查询似乎不起作用..

4

1 回答 1

2

尝试这个:

users_ids = Post.where(:forum_id => 1).collect { |c| c.user_id }
@users = User.where('topic_id = ? and id not in (?) ', @topic.id, users_ids)

另外,我建议您进行一些更改:

  • 使用 pluck 而不是 collect (pluck 在数据库级别)(pluck doc ; pluck vs. collect

    users_ids = Post.where(:forum_id => 1).pluck(:user_id)

  • 在 where 子句中命名表以避免模棱两可的调用(例如在 where 链接中):

    User.where('users.topic_id = ? AND users.id NOT IN (?)', @topic.id, users_ids)

最终代码:

users_ids = Post.where(:forum_id => 1).pluck(:user_id)
@users = User.where('users.topic_id = ? AND users.id NOT IN (?)', @topic.id, users_ids)
于 2013-05-03T13:40:52.367 回答