Reputation: 37
I'm looking to see if there is a better way to write the following ActiveRecord query.
@posts = Post.select {|x| x.section.nil?}
What I'm doing with this query is searching through posts and just selecting the posts that no longer have sections associated and are left orphaned.
Is there a better way to do this? I'm using rails 3.2.
Thanks so much.
Upvotes: 1
Views: 347
Reputation: 51191
This should work:
Post.joins('left outer join sections on sections.id = posts.section_id').where('sections.id is null and posts.section_id is not null')
or in shorter way, using eager_load
:
Post.eager_load(:section).where('sections.id is null and posts.section_id is not null')
Upvotes: 2