【发布时间】:2011-01-06 22:10:56
【问题描述】:
虽然我不是一个完整的 Ruby/Rails 新手,但我仍然很年轻,我正在尝试弄清楚如何构建一些模型关系。我能想到的最简单的例子就是烹饪“食谱”的概念。
食谱由一种或多种成分以及每种成分的相关数量组成。假设我们在所有成分的数据库中有一个主列表。这表明了两个简单的模型:
class Ingredient < ActiveRecord::Base
# ingredient name,
end
class Recipe < ActiveRecord::Base
# recipe name, etc.
end
如果我们只想将食谱与成分相关联,只需添加适当的 belongs_to 和 has_many 即可。
但是,如果我们想将附加信息与这种关系关联起来怎么办?每个Recipe 有一个或多个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
【问题讨论】:
标签: ruby-on-rails activerecord has-many has-many-through