1

私は完全な Ruby/Rails 初心者ではありませんが、まだかなり未熟で、モデルの関係を構築する方法を理解しようとしています。私が考えることができる最も簡単な例は、料理の「レシピ」のアイデアです。

レシピは、1 つまたは複数の材料と、各材料に関連付けられた数量で構成されます。データベースにすべての成分のマスターリストがあるとします。これは、次の 2 つの単純なモデルを示唆しています。

class Ingredient < ActiveRecord::Base
  # ingredient name, 
end

class Recipe < ActiveRecord::Base
  # recipe name, etc.
end

Recipes を Ingredients に関連付けるだけなら、適切なbelongs_toandを追加するだけで簡単has_manyです。

しかし、追加情報をその関係に関連付けたい場合はどうすればよいでしょうか? それぞれRecipeに が 1 つ以上Ingredientsありますが、の数量を示したいと思いますIngredient

それをモデル化するRailsの方法は何ですか? それはaの線に沿ったものhas_many throughですか?

class Ingredient < ActiveRecord::Base
  # ingredient name
  belongs_to :recipe_ingredient
end

class RecipeIngredient < ActiveRecord::Base
  has_one :ingredient
  has_one :recipe
  # quantity
end

class Recipe < ActiveRecord::Base
  has_many :recipe_ingredients
  has_many :ingredients, :through => :recipe_ingredients
end
4

2 に答える 2

5

Recipe と Ingredients は has と belongs to many の関係にありますが、リンク用の追加情報を保存したいと考えています。

基本的に、探しているのはリッチ結合モデルです。しかし、has_and_belongs_to_many の関係は、必要な追加情報を格納できるほど柔軟ではありません。代わりに has_many :through relatinship を使用する必要があります。

これが私がそれを設定する方法です。

レシピ列: 説明

class Recipe < ActiveRecord::Base
  has_many :recipe_ingredients
  has_many :ingredients, :through => :recipe_ingredients
end

レシピの材料列: レシピ ID、材料 ID、数量

class RecipeIngredients < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient
end

成分列: 名前

class Ingredient < ActiveRecord::Base
  has_many :recipe_ingredients
  has_many :recipes, :through => :recipe_ingredients
end

これにより、実行しようとしているものの基本的な表現が提供されます。RecipeIngredients に検証を追加して、各成分がレシピごとに 1 回リストされていることを確認し、コールバックを追加して重複を 1 つのエントリにまとめることができます。

于 2010-01-19T18:01:00.503 に答える
0

http://railsbrain.com/api/rails-2.3.2/doc/index.html?a=M001888&name=has_and_belongs_to_many

http://railsbrain.com/api/rails-2.3.2/doc/index.html?a=M001885&name=has_many

どうですか:

  1. class Ingredient (レシピに属し、多くの材料レシピカウントを持っています)
  2. class Recipe (材料が多く、材料のレシピ数が多い)
  3. クラス IngredientRecipeCount (成分に属し、レシピに属します)

これは Rails のやり方というよりも、データベース内のデータ間にもう 1 つの関係を確立するだけです。各材料はレシピごとに 1 つのカウントしかなく、各レシピは材料ごとに 1 つのカウントしかないため、実際には「多くのものを持っている」とは言えません。どちらも同じカウントです。

于 2010-01-19T17:49:46.973 に答える