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
# or 
Parent.includes(:children).where(" 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



Send Me A Message

I would love to get in touch and talk about your next project. Feel free to send a message and I will get back to you shortly.

Get Connected