-
-
Save adamjt/558128 to your computer and use it in GitHub Desktop.
class Kitchen < ActiveRecord::Base | |
has_many :cups | |
end | |
class Cup < ActiveRecord::Base | |
has_many :liquids | |
belongs_to :kitchen | |
end | |
class Liquid < ActiveRecord::Base | |
belongs_to :cup | |
has_one :kitchen. :through => :cup | |
end |
For a first revision I'd set up a named scope on liquids:
named_scope :for_kitchen, lambda { |kitchen| { :joins => 'cup on cup.kitchen_id=kitchen.id', :conditions => ['cup.id in (?)',kitchen.cups.collect(&:id)] } }
So then:
Liquid.for_kitchen(Kitchen.first).all
The &id collect might be redundant.
My shot, rails 2.3 style:
Liquid.all(:joins => {:cup => kitchen}, :conditions => {:kitchens => {:id => KITCHEN_ID}, :liquids => {:hot => true}})
I figured this out using the Rails 3 syntax. Seems to be working properly for now.
scope :for_kitchen, lambda {|kitchen| joins(:cup => :kitchen).where('kitchens.id = ?', kitchen.id)}
scope is a good way to go but this should work as well in rails 3. have not tested but should work but maybe not the most efficient thing ever. just cool you can do it.
first load kitchen with your id:
kitchen.cups.liquids.where(:hot => true)
I want to find all liquids with :hot => true given a Kitchen id. What would my query be?