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);

上記のレールのクエリは機能していないようです..

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)

また、いくつかの変更を加えることをお勧めします。

  • collect の代わりに pluck を使用します (pluck は DB レベルにあります)( 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 に答える