Created
June 22, 2011 16:05
-
-
Save ericcf/1040440 to your computer and use it in GitHub Desktop.
example associations between physical and proxy models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Ingredient < ActiveResource::Base | |
def recipes | |
# returns all recipes with this ingredient as a component | |
Recipe.joins(components).merge(components) | |
end | |
def components | |
Component.where :ingredient_id => id | |
end | |
end | |
Class Component < ActiveRecord::Base | |
belongs_to :recipe | |
def ingredient | |
Ingredient.find ingredient_id | |
end | |
end | |
Class Recipe < ActiveRecord::Base | |
has_many :components | |
def ingredients | |
# this might be better implemented by adding | |
# a non-restful controller action on the server side | |
component_ingredient_ids = components.map &:ingredient_id | |
Ingredient.all.select { |i| component_ingredient_ids.include? i.id } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment