Rails:has_many有更多细节吗?

org*_*gie 1 activerecord ruby-on-rails has-many has-many-through

虽然我不是一个完整的Ruby/Rails newb,但我仍然很绿,我正在试图弄清楚如何构建一些模型关系.我能想到的最简单的例子是烹饪"食谱"的想法.

配方由一种或多种成分和每种成分的相关数量组成.假设我们在数据库中有所有成分的主列表.这表明两个简单的模型:

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

class Recipe < ActiveRecord::Base
  # recipe name, etc.
end
Run Code Online (Sandbox Code Playgroud)

如果我们只是想用配方原料联系起来,这是因为作为simpling添加适当的belongs_tohas_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
Run Code Online (Sandbox Code Playgroud)

EmF*_*mFi 5

食谱和配料有一个属于许多关系,但你想存储链接的附加信息.

基本上你正在寻找的是一个丰富的连接模型.但是,has_and_belongs_to_many关系不够灵活,无法存储您需要的其他信息.相反,你需要使用has_many:通过relatinship.

我就是这样设置的.

食谱栏目:说明

class Recipe < ActiveRecord::Base
  has_many :recipe_ingredients
  has_many :ingredients, :through => :recipe_ingredients
end
Run Code Online (Sandbox Code Playgroud)

recipe_ingredients列:recipe_id,ingredient_id,数量

class RecipeIngredients < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient
end
Run Code Online (Sandbox Code Playgroud)

成分栏:名称

class Ingredient < ActiveRecord::Base
  has_many :recipe_ingredients
  has_many :recipes, :through => :recipe_ingredients
end
Run Code Online (Sandbox Code Playgroud)

这将提供您要做的事情的基本表示.您可能希望向RecipeIngredients添加验证,以确保每个配方列出每个成分一次,并将回复折叠到一个条目中.