[英]Add Quantity to a Recipe habtm Ingredients Relation
I wanted to build a basic cookbook. 我想建立一个基本的食谱。 With a Recipes habtm Ingredients Relation. 与食谱habtm成分关系。
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. 但我不知道其他解决方案。
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. 我认为这可能很难看,因为您对类名的选择导致您经常键入“ recipe.recipe_ingredients.ingredient”。 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: 我将其重命名为:
Recipe
has_many :ingredients
has_many :items, :through => :ingredients
Ingredient
#fields - recipe_id, item_id, quantity(string)
belongs_to :recipe
belongs_to :item
Item
has_many :ingredients
has_many :recipes, :through => :ingredients
Now on your view page you can say 现在,您可以在查看页面上说
<h2><%= recipe.name %></h2>
<dl>
<% @recipe.ingredients.each do |ingredient| %>
<dt><%= ingredient.item.name %></dt>
<dd><%= ingredient.quantity %></dd>
<% end %>
</dl>
I guess you were missing has_many:through in receipe model 我想您在receipe模型中缺少了has_many:through
class Receipe < ActiveRecord::Base 类Receipe <ActiveRecord :: Base
has_many :receipe_ingredients has_many:receipe_ingredients
has_many :ingredients, :through => :receipe_ingredients has_many:ingredients,:through =>:receipe_ingredients
end 结束
class Ingredient < ActiveRecord::Base 类成分<ActiveRecord :: Base
has_many :receipe_ingredients has_many:receipe_ingredients
has_many :receipes, :through => :receipe_ingredients has_many:receipes,:through =>:receipe_ingredients
end 结束
class ReceipeIngredient < ActiveRecord::Base 类ReceipeIngredient <ActiveRecord :: Base
belongs_to :receipe 所属:收据
belongs_to :ingredient 归属于:ingredient
end 结束
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.