简体   繁体   中英

Includes in multiple belongs_to association chain (avoiding N+1)

I have models like below:

class Foo < ActiveRecord::Base
  has_many: :bars
end

class Bar < ActiveRecord::Base
  belongs_to: :foo
  has_many: :bazs
end

class Baz < ActiveRecord::Base
  belongs_to: :bar
end

How can I can includes foo in my baz query? (Something like Baz.includes(:foo).where(condition: 'condition').map(&:foo) )

You'll have to get a join to foo through the bar association. Something similar to this should work for you in ActiveRecord .

Baz.joins(bar: :foo).where(foos: { SOME_FOO_COLUMN: 'condition' })

This will return a collection of Baz 's where your Foo condition is true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM