[ACCEPTED]-find all that are nil in the association-ruby-on-rails-3
Accepted answer
Post.where("id not in (select post_id from users)")
0
Learned this one just today:
Post.eager_load(:users).merge(User.where(id: nil))
Works with Rails 2 4+ at least.
Update:
In Rails 5+, you can 1 use left_joins
instead:
Post.left_joins(:users).merge(User.where(id: nil))
If you need something that is fast, employ 1 a SQL statement like:
SELECT *
FROM posts p
LEFT OUTER JOIN users u ON p.id = u.post_id
WHERE u.id IS null
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)
0
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))
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
end
end
i guess a sql with in can cause performance 2 problems if database table has many rows. careful 1 with that
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.