alpheus
alpheus

Reputation: 989

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

Upvotes: 3

Views: 964

Answers (1)

Yuri  Barbashov
Yuri Barbashov

Reputation: 5437

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

Upvotes: 7

Related Questions