1

虽然我不是一个完整的 Ruby/Rails 新手,但我仍然很年轻,我正在尝试弄清楚如何构建一些模型关系。我能想到的最简单的例子是烹饪“食谱”的想法。

食谱由一种或多种成分以及每种成分的相关数量组成。假设我们在所有成分的数据库中有一个主列表。这表明了两个简单的模型:

class Ingredient < ActiveRecord::Base
  # ingredient name, 
end

class Recipe < ActiveRecord::Base
  # recipe name, etc.
end

如果我们只是想将食谱与成分相关联,那就像添加适当的belongs_toand一样简单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
4

2 回答 2

5

Recipes 和 Ingredients 有一个 has 和属于 many 关系,但您想存储附加信息以进行链接。

本质上,您正在寻找的是丰富的联接模型。但是,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、component_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 添加验证,以确保每种成分在每个配方中列出一次,并通过回调将重复项合并到一个条目中。

于 2010-01-19T18:01:00.503 回答
0

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

怎么样:

  1. 类成分(属于配方,有许多成分配方计数)
  2. 类食谱(有很多成分,有很多成分食谱计数)
  3. class IngredientRecipeCount(属于配料,属于配方)

这与其说是 Rails 的方式,不如说是在数据库中的数据之间再建立一种关系。这并不是真正的“拥有并属于许多”,因为每种成分每个配方只有一个计数,每个配方每个成分一个计数。这是相同的计数。

于 2010-01-19T17:49:46.973 回答