1

I have these 3 models with a has_many through relation:

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

But if I have 10 wines, I will see 10 requests in my logs like these ones after the main Wine request:

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

How can I load the grapes in the main request to not have a request per grape ?

alex.bour
  • 2,842
  • 9
  • 40
  • 66

1 Answers1

0

Try this:

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

If it works, don't ask me why ;)