关联如下:

#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

我想这样做会导致N + 1错误:
@pets = Pet.where(species: "Dog").includes(:pet_store)
@pets.each do |pet|
  pet.pet_store.employees.each do |employee|
    puts employee.name
  end
end

这会导致n+1错误,因为必须对每个employee进行查询。我想eager load间接关联的employees但是,我不能简单地includes(:employees),因为apetemployees没有直接关联怎么能做到?

最佳答案

您可以使用:

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

查询语言上的Rails指南非常棒这是docs on eager-loading

关于ruby-on-rails - 渴望负载间接关联Rails,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31237939/

10-13 06:03