虽然我不是一个完整的 Ruby/Rails 新手,但我仍然很年轻,我正在尝试弄清楚如何构建一些模型关系。我能想到的最简单的例子是烹饪“食谱”的想法。
食谱由一种或多种成分以及每种成分的相关数量组成。假设我们在所有成分的数据库中有一个主列表。这表明了两个简单的模型:
class Ingredient < ActiveRecord::Base
# ingredient name,
end
class Recipe < ActiveRecord::Base
# recipe name, etc.
end
如果我们只是想将食谱与成分相关联,那就像添加适当的belongs_to
and一样简单has_many
。
但是,如果我们想将附加信息与这种关系相关联呢?每个Recipe
都有一个或多个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