私は完全な Ruby/Rails 初心者ではありませんが、まだかなり未熟で、モデルの関係を構築する方法を理解しようとしています。私が考えることができる最も簡単な例は、料理の「レシピ」のアイデアです。
レシピは、1 つまたは複数の材料と、各材料に関連付けられた数量で構成されます。データベースにすべての成分のマスターリストがあるとします。これは、次の 2 つの単純なモデルを示唆しています。
class Ingredient < ActiveRecord::Base
# ingredient name,
end
class Recipe < ActiveRecord::Base
# recipe name, etc.
end
Recipes を Ingredients に関連付けるだけなら、適切なbelongs_to
andを追加するだけで簡単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