Ruby on rails 将数量添加到配方habtm成分关系中
我想写一本基本的食谱。与配方habtm成分相关 我的第一次尝试是这样的Ruby on rails 将数量添加到配方habtm成分关系中,ruby-on-rails,design-patterns,has-and-belongs-to-many,recipe,Ruby On Rails,Design Patterns,Has And Belongs To Many,Recipe,我想写一本基本的食谱。与配方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 =
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
这感觉很难看。但我不知道其他解决方案。作为一种模式/方法,我觉得很好。我想这可能会让人觉得很难看,因为你选择的类名让你经常输入“recipe.recipe\u components.component”。对我来说,“配料”是指食谱中使用的食物/液体/任何东西,因此连接表应称为“配料”。每种成分都有数量和与“产品”或“项目”或类似内容的链接 我将它改名为:
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
现在在你的浏览页面上你可以说
<h2><%= recipe.name %></h2>
<dl>
<% @recipe.ingredients.each do |ingredient| %>
<dt><%= ingredient.item.name %></dt>
<dd><%= ingredient.quantity %></dd>
<% end %>
</dl>
作为一种模式/方法,我觉得很好。我想这可能会让人觉得很难看,因为你选择的类名让你经常输入“recipe.recipe\u components.component”。对我来说,“配料”是指食谱中使用的食物/液体/任何东西,因此连接表应称为“配料”。每种成分都有数量和与“产品”或“项目”或类似内容的链接 我将它改名为:
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
现在在你的浏览页面上你可以说
<h2><%= recipe.name %></h2>
<dl>
<% @recipe.ingredients.each do |ingredient| %>
<dt><%= ingredient.item.name %></dt>
<dd><%= ingredient.quantity %></dd>
<% end %>
</dl>
我猜您在receipe模型中错过了很多:通过 类Receipe
结束我猜你在receipe模型中错过了很多:通过 类Receipe
结束Yay键入菜谱。菜谱。。。这很糟糕。谢谢键入食谱。食谱。。。这很糟糕。谢谢