レール:has_many には追加の詳細が含まれていますか?
-
21-09-2019 - |
質問
私は Ruby/Rails の完全な初心者ではありませんが、まだかなり未熟で、モデルの関係を構築する方法を見つけようとしています。私が思いつく最も単純な例は、料理の「レシピ」のアイデアです。
レシピは、1 つ以上の材料と、各材料の関連する量で構成されます。データベースにすべての成分のマスター リストがあると仮定します。これは 2 つの単純なモデルを示唆しています。
class Ingredient < ActiveRecord::Base
# ingredient name,
end
class Recipe < ActiveRecord::Base
# recipe name, etc.
end
レシピを材料に関連付けたいだけであれば、適切なパラメータを追加するだけで簡単です。 belongs_to
そして has_many
.
しかし、追加情報をその関係に関連付けたい場合はどうすればよいでしょうか?それぞれ Recipe
1 つ以上あります Ingredients
, 、ただし、の量を示したいのです。 Ingredient
.
それをモデル化する Rails の方法は何ですか?それは何かの線に沿ったものですか? 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
解決
レシピや食材があり、多くの関係に属していますが、あなたは、リンクの追加情報を格納したいです。
は基本的に何を求めているの豊富な参加モデルです。しかし、has_and_belongs_to_manyアソシエーションの関係は、必要な追加情報を格納するための柔軟な十分ではありません。代わりにあなたがにhas_manyを使用する必要があります:。relatinshipを通じて
これは私がそれを設定する方法をされています。
レシピ列:指示
class Recipe < ActiveRecord::Base
has_many :recipe_ingredients
has_many :ingredients, :through => :recipe_ingredients
end
recipe_ingredients列:recipe_id、ingredient_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つのエントリに重複を折るためにコールバックしたい場合があります。
他のヒント
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
どうでしょうか:
- クラスIngredient(レシピに属し、多くの成分レシピ数を持ちます)
- クラスレシピ (多くの材料があり、多くの材料レシピ数があります)
- class IngredientRecipeCount (材料に属する、レシピに属する)
これは Rails のやり方というよりは、データベース内のデータ間の関係をもう 1 つ確立するだけです。各材料にはレシピごとに 1 つのカウントしかなく、各レシピには材料ごとに 1 つのカウントがあるため、実際には「多数のものを持ち、多数のものに属する」というわけではありません。これは同じカウントです。