0

私は基本的な料理本を作りたかった。Recipes habtm Ingredients Relation 付き。

私の最初の試みはこのようなものでした。

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

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

これは醜い気がします。しかし、私は他の解決策を知りません。

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 が欠落していたと思います

class Receipe < ActiveRecord::Base

has_many :receipe_ingredients

has_many :ingredients, :through => :receipe_ingredients

終わり

class Ingredient < ActiveRecord::Base

has_many :receipe_ingredients

has_many :receipes, :through => :receipe_ingredients

終わり

class ReceipeIngredient < ActiveRecord::Base

所属先:領収書

所属先:成分

終わり

于 2010-11-25T10:52:48.750 に答える