我想制作一本基本的食谱。与食谱 habtm 成分关系。
我的第一次尝试是这样的。
class Recipe < ActiveRecord::Base
# title, description
has_many :recipe_ingredients
end
class Ingredient < ActiveRecord::Base
# name, unit
has_many :recipe_ingredients
has_many :recipes, :through => :recipe_ingredients
end
class RecipeIngredient < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
attr_accessible :amount
end
并手工创建了关系
RecipeIngredient.create(:recipe_id => 1, :ingredient_id => 2, :amount => 100)
recipe.recipe_ingredients.amout
recipe.recipe_ingredients.ingredient.unit
recipe.recipe_ingredients.ingredient.name
这感觉很丑。但我不知道任何其他解决方案。