Rails:has_many有额外的细节吗?
虽然我不是一个完整的Ruby / Rails newb,但我仍然很绿,我正在试图弄清楚如何构建一些模型关系。 我能想到的最简单的例子是烹饪“食谱”的想法。
配方由一种或多种成分和每种成分的相关数量组成。 假设我们在所有成分的数据库中都有一个主列表。 这表明两个简单的模型:
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 :recipe_ingredients end
食谱和配料有一个属于许多关系,但你想存储链接的附加信息。
基本上你正在寻找的是一个丰富的连接模型。 但是,has_and_belongs_to_many关系不够灵活,无法存储您需要的其他信息。 相反,你需要使用has_many:through 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添加validation,以确保每个配方列出每个成分一次,并将回复折叠到一个条目中。
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
怎么样:
- 类成分(属于食谱,有许多成分配方)
- class Recipe(有很多成分,有很多成分配方)
- class IngredientRecipeCount(属于成分,属于食谱)
这不仅仅是Rails的方式,而是在数据库中建立一个更多的关系。 它不是真的“有并且属于许多”,因为每种配方每个配方只有一个计数,每个配方每个配料一个计数。这是相同的计数。