1

私はこれらの3つのモデルにhas_manythroughリレーションを持っています:

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

ブドウごとのリクエストがないように、メインリクエストでブドウをロードするにはどうすればよいですか?

4

1 に答える 1

0

これを試して:

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

それが機能する場合は、理由を聞かないでください;)

于 2012-05-03T16:17:18.683 に答える