Rails - 为什么在这种情况下Eager加载不起作用?

时间:2012-03-30 10:40:49

标签: ruby-on-rails eager

我有这3个带有has_many关系的模型:

class Wine < ActiveRecord::Base
  has_many :varietals, :conditions => "varietals.status = 1"
  has_many :grapes, :through => :varietals
end

class Grape < ActiveRecord::Base
  has_many :varietals
  has_many :wines, :through => :varietals
end

class Varietal < ActiveRecord::Base
  belongs_to :wine
  belongs_to :grape
end

@records = Wine.where(conditions).includes({:varietals => :grape})

但是,如果我有10种葡萄酒,我会在主要葡萄酒请求之后在我的日志中看到10个请求:

  Grape Load (0.6ms)  SELECT `grapes`.* FROM `grapes` INNER JOIN `varietals` ON `grapes`.id = `varietals`.grape_id WHERE ((`varietals`.wine_id = '98DF2CEC-61CC-4B22-B40D-620AADF650D2') AND ((varietals.status = 1)))

如何在主要要求中加载葡萄,以便每个葡萄都没有要求?

1 个答案:

答案 0 :(得分:0)

试试这个:

Wine.includes(:varietals).includes(:grapes).where(conditions)

如果有效,请不要问我原因;)