2013-05-03 40 views
1

我試圖選擇在論壇列表中沒有帖子的用戶。爲此,我寫了這樣的Rails3 NOT IN查詢以字符串作爲值

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中似乎不起作用..

回答

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) 

另外,我建議你做一些修改:

  • 使用採摘,而不是收集(拔毛是在DB級)(pluck doc; pluck vs. collect

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

  • 名稱在表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)