Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - children of multiple parents

If I have two models - parent and child, and parent has_many children, and I have an array of parents and want to retrieve all of the children for all of those parents, is there a way I can do this in Rails without writing the SQL statement manually?

This is what I want to do:

@parents = Parent.where("[various conditions]")
@children = @parents.children
like image 368
alpheus Avatar asked Nov 29 '25 16:11

alpheus


1 Answers

Child.where(:parent_id => @parents.pluck(:id))

or

@parent_ids = Parent.where("[various conditions]").pluck(:id)
Child.where(:parent_id => @parent_ids}

or u can use join

Child.join(:parent).merge(Parent.where("[various conditions]")) #!!readonly
like image 139
Yuri Barbashov Avatar answered Dec 02 '25 07:12

Yuri Barbashov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!