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

Posted by Weston Ganger

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
Parent.join(:children).uniq.all
# 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:

Article Topic:Software Development - Rails

Date:December 20, 2016

Recommended Posts