0

我想制作一本基本的食谱。与食谱 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

这感觉很丑。但我不知道任何其他解决方案。

4

2 回答 2

3

作为模式/方法,对我来说看起来不错。我认为这可能会让人觉得很难看,因为您选择的类名会导致您经常输入“recipe.recipe_ingredients.ingredient”。对我来说,“成分”是食谱中使用的食物/液体/任何东西,因此连接表应该称为“成分”。每种成分都有数量并链接到“产品”或“项目”或类似的东西。

我会这样重命名它:

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>
于 2010-11-25T10:50:34.980 回答
0

我猜你在收据模型中缺少 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

属于_to :receipe

属于_to:成分

结尾

于 2010-11-25T10:52:48.750 回答