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.
Parent.joins(:children).uniq.all
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With