将数量添加到食谱 habtm 成分关系
我想写一本基本的食谱。与食谱 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
这感觉很丑。但我不知道还有其他解决方案。
I wanted to build a basic cookbook. With a Recipes habtm Ingredients Relation.
My first attempt was like this.
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
And created the Relation by Hand
RecipeIngredient.create(:recipe_id => 1, :ingredient_id => 2, :amount => 100)
recipe.recipe_ingredients.amout
recipe.recipe_ingredients.ingredient.unit
recipe.recipe_ingredients.ingredient.name
This feels ugly. But I don't know any other solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
作为一种模式/方法,我觉得很好。我认为这可能感觉很丑,因为您选择的类名会导致您多次输入“recipe.recipe_ingredients.ingredient”。对我来说,“成分”是食谱中使用的食物/液体/任何东西,因此连接表应该称为“成分”。每种成分都有一个数量并链接到“产品”或“物品”或类似的东西。
我将其重命名为:
现在在您的视图页面上您可以说
Looks fine to me, as a schema/approach. I think it might just feel ugly because your choice of class name leads you to type "recipe.recipe_ingredients.ingredient" a lot. To me, an 'ingredient' is the food/liquid/whatever AS IT IS USED IN THE RECIPE, so the join table should be called 'ingredients'. Each ingredient has a quantity and links to a 'product' or an 'item' or something similar.
I would rename it thus:
Now on your view page you can say
中缺少 has_many:through
我猜您在收据模型类 Receipe < ActiveRecord::Base
has_many :receipe_ingredients
has_many :ingredients, :through => :receipe_ingredients
结束
类成分 < ActiveRecord::Base
has_many :receipe_ingredients
has_many :receipes, :through => :receipe_ingredients
结束
类 ReceipeIngredient < ActiveRecord::Base
属于 : 收据
属于 : 成分
结束
I guess you were missing has_many:through in receipe model
class Receipe < ActiveRecord::Base
has_many :receipe_ingredients
has_many :ingredients, :through => :receipe_ingredients
end
class Ingredient < ActiveRecord::Base
has_many :receipe_ingredients
has_many :receipes, :through => :receipe_ingredients
end
class ReceipeIngredient < ActiveRecord::Base
belongs_to :receipe
belongs_to :ingredient
end