简体   繁体   中英

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?

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 .

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