Neil
Neil

Reputation: 5178

Eager Load indirect associations Rails

Associations are below:

#app/models/pet.rb
class Pet < ActiveRecord::Base
  belongs_to :pet_store
end

#app/models/pet_store.rb
class PetStore < ActiveRecord::Base
    has_many :pets, dependent: :destroy
    has_many :employees, dependent: :destroy
end

#app/models/employee.rb
class Employee < ActiveRecord::Base
  belongs_to :pet_store
end

I want to do something like so which would cause an N + 1 error:

@pets = Pet.where(species: "Dog").includes(:pet_store)
@pets.each do |pet|
  pet.pet_store.employees.each do |employee|
    puts employee.name
  end
end

This causes an N+1 error because a query must be made for each employee. I would like to eager load the indirect associated employees. However, I cannot simply includes(:employees) because a pet has no direct association to employees. How can this be done?

Upvotes: 1

Views: 160

Answers (1)

Taryn East
Taryn East

Reputation: 27747

You can with:

@pets = Pet.includes(:pet_store => :employees)

The Rails Guide on the Query Language is great. Here's the docs on eager-loading.

Upvotes: 3

Related Questions