Skip to content

Instantly share code, notes, and snippets.

@ericcf
Created June 22, 2011 16:05
Show Gist options
  • Save ericcf/1040440 to your computer and use it in GitHub Desktop.
Save ericcf/1040440 to your computer and use it in GitHub Desktop.
example associations between physical and proxy models
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