1

I am trying to select users who don't have post in the forum list. For that I wrote a query like this

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}")

This code throws mysql error, and in my log

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]'

In mysql I execute the following query, and got the expected result

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

The above query in rails doesn't seem to work..

Achaius
  • 5,904
  • 21
  • 65
  • 122

1 Answers1

2

Try this:

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)

Also, I advice you to make some changes:

  • Use pluck instead of collect (pluck is on the DB level)(pluck doc ; pluck vs. collect)

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

  • name the table in the where clause to avoid ambiguous calls (in where chaining for example):

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

The final code:

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)
Community
  • 1
  • 1
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117