How To Find Records Based On Has_many Relationship Being Empty Or Not In Rails

Posted by Weston Ganger on December 20, 2016

Sometimes in your Rails app you may want to find records that have no has_many items or has at least one item. Heres how to do this:

### Find all records with at least one child
# or 
Parent.includes(:children).where("children.id IS NOT NULL")
# or Rails 5
Parent.left_outer_joins(:children).where.not(children: {id: nil})

### Find all records with no children
Parent.includes(:children).where(children: {id: nil})
# or Rails 5
Parent.left_outer_joins(:children).where(children: {id: nil})

Related External Links:

Posted in Rails and Tagged with rails active_record 

Want me to help develop your next project or application?

Contact Us

Specializing in Ruby-on-Rails, Javascript, Multi-Platform Electron Desktop Apps and Hybrid Cordova Mobile Apps.

Recommended Posts