ekiyanov
ekiyanov

Reputation: 461

Rails select all children of children

My class S has many class A who has many B.

I can get all A's for my S (S.As) I can iterate over this array and get Bs for every A.

something like

S.As.each do |aa| 
    aa.Bs
end 

How can I do the same without using 'each'?

Upvotes: 3

Views: 3192

Answers (2)

Athar
Athar

Reputation: 3268

This will work in one line without each

S.As.collect(&:Bs)

Upvotes: 6

Kkulikovskis
Kkulikovskis

Reputation: 2088

If the problem is with N+1 Queries, I suggest using includes

Right now a new query is generated for each As to get it's Bs.

If you write it like this:

S.As.includes(:Bs).each do |aa| 
    aa.Bs
end 

you will get way less queries, because all Bs will be preloaded.

map and collect won't change anything in this case.

Upvotes: 3

Related Questions