Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to get objects with at least one child?

Tags:

After googling, browsing SO and reading, there doesn't seem to be a Rails-style way to efficiently get only those Parent objects which have at least one Child object (through a has_many :children relation). In plain SQL:

SELECT *   FROM parents  WHERE EXISTS (                SELECT 1                  FROM children                 WHERE parent_id = parents.id) 

The closest I've come is

Parent.all.reject { |parent| parent.children.empty? } 

(based on another answer), but it's really inefficient because it runs a separate query for each Parent.

like image 967
l0b0 Avatar asked Mar 29 '12 09:03

l0b0


1 Answers

Parent.joins(:children).uniq.all 
like image 50
Chris Bailey Avatar answered Oct 07 '22 00:10

Chris Bailey