Ilya
Ilya

Reputation: 13487

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))

Upvotes: 0

Views: 130

Answers (1)

Matt Polito
Matt Polito

Reputation: 9756

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.

Upvotes: 1

Related Questions