Eager Load间接关联Rails

时间:2015-07-06 04:47:30

标签: ruby-on-rails ruby activerecord

协会如下:

FileNotFoundException: Bulkload dir /user/hadoop/outputfile not found

我想做类似的事情会导致#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

这会导致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 进行查询。我想employee间接关联的eager load。但是,我不能简单地employees,因为includes(:employees)pet没有直接关联。怎么办呢?

1 个答案:

答案 0 :(得分:3)

您可以:

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

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