[ACCEPTED]-find all that are nil in the association-ruby-on-rails-3

Accepted answer
Score: 30
Post.where("id not in (select post_id from users)")


Score: 22

Learned this one just today:

Post.eager_load(:users).merge(User.where(id: nil))

Works with Rails 2 4+ at least.


In Rails 5+, you can 1 use left_joins instead:

Post.left_joins(:users).merge(User.where(id: nil))
Score: 2

If you need something that is fast, employ 1 a SQL statement like:

FROM posts p 
LEFT OUTER JOIN users u ON p.id = u.post_id 
WHERE u.id IS null
Score: 2

something like that:

p = Post.arel_table
u = User.arel_table

posts = Post.find_by_sql(p.join(u).on(p[:user_id].eq(u[:p_id])).where(u[:id].eq(nil)).to_sql) 


Score: 2

I know this is tagged as Rails 3, but if 2 you are using Rails 4, I've been doing it 1 like this.

Post.where.not(user_id: User.pluck(:id))
Score: 1

Post.first.users.empty? should be sufficient if users returns an 2 array.

If you want to check for each post 1 you could do

Post.each do |p|
  if p.users.empty?
    do whatever
Score: 1

i guess a sql with in can cause performance 2 problems if database table has many rows. careful 1 with that

More Related questions