1

我有这 3 个模型与 has_many through 关系:

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 个请求,比如在主要的 Wine 请求之后:

  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)))

如何在主请求中加载葡萄以使每个葡萄都没有请求?

4

1 回答 1

0

尝试这个:

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

如果它有效,不要问我为什么;)

于 2012-05-03T16:17:18.683 回答