虽然我不是一个完整的红宝石/轨道福利局,我还漂亮的绿色和我试图找出如何结构的一些模型的关系。最简单的例子我能想到的是"菜谱"的用于烹饪。

一方由一个或多个成分和相关数量的每一个成分。假设我们有一个总表中数据库的所有成分。这表明两个简单的模型:

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

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

如果我们只是想来关联的食谱用的成分,这是因为simpling如加入相应的 belongs_tohas_many.

但是,如果我们想要联系的其他信息与关系?每 Recipe 有一个或更多 Ingredients, 但是我们想要表明的数量 Ingredient.

什么是轨道的方式模型,该模型?这是沿线的东西了 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
有帮助吗?

解决方案

食谱和配料有有属于一对多的关系,但你要存储链接的附加信息。

基本上你正在寻找的是一个丰富的连接模型。但是,一个has_and_belongs_to_many关系不够灵活来存储您所需要的附加信息。相反,你将需要使用的has_many:通过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,以确保每一种成分列出每个配方一次,回调折叠成重复一个条目。

其他提示

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. 类的成分(属于配方,有许多ingredientrecipecounts)
  2. 类配方(有许多成分,有许多ingredientrecipecounts)
  3. 类IngredientRecipeCount(所属成分,属于食谱)

这不是那么多轨道方式,因为只有建立一个更之间的关系数据库中的数据。它不是一个真正的"有属于许多",因为每个成分只有一个计,每食谱,以及每个配方的一种计数每分..这是相同的数量。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top