Skip to content

Instantly share code, notes, and snippets.

@adamjt
Created August 30, 2010 22:06
Show Gist options
  • Save adamjt/558128 to your computer and use it in GitHub Desktop.
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
@adamjt
Copy link
Author

adamjt commented Aug 30, 2010

I want to find all liquids with :hot => true given a Kitchen id. What would my query be?

@adrianpike
Copy link

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.

@derencius
Copy link

My shot, rails 2.3 style:

Liquid.all(:joins => {:cup => kitchen}, :conditions => {:kitchens => {:id => KITCHEN_ID}, :liquids => {:hot => true}})

@adamjt
Copy link
Author

adamjt commented Aug 30, 2010

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

@batchblue
Copy link

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment