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 

Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts