【发布时间】:2012-08-25 15:54:05
【问题描述】:
我一直在努力思考这些关联,但我遇到了一些障碍。我正在开发的应用程序目前有 2 个模型:成分和配方。每一个背后的逻辑如下:
成分模型包含有关食品的信息,例如名称、批量价格等。 配方模型包含配方名称、制备说明和成分列表(以及配方所需的量)。
在研究了这里的一些问题并观看了一些 railscasts 之后,我确定 has_many_through 关系可能更适合我正在尝试做的事情,因为我想包含有关成分的其他信息在配方中(所需数量)。
基于我在这方面的有限经验,我想这样处理:
class Recipe < ActiveRecord::Base
has_many :ingredients_recipes
has_many :ingredients, :through => :ingredients_recipes
end
class Ingredient_Recipe < ActiveRecord::Base
belongs_to :ingredient
belongs_to :recipe
end
class Ingredient < ActiveRecord::Base
has_many :ingredients_recipes
has_many :recipes, :through => :ingredients_recipes
end
Ingredient_recipes 表将包含类似于以下字段的字段:recipe_id、component_id、component_qty(用于存储配方中特定成分的含量)
根据我上面提到的功能,这是以代码方式处理它的正确方法吗?任何帮助将不胜感激。谢谢!
编辑 我还希望能够从配方表中将这些新成分添加到配方中。这是否需要任何额外的东西,比如必须为 through 表做 Accepts_nested_attributes_,还是 Rails 可以自己处理?
【问题讨论】:
标签: ruby-on-rails-3 activerecord has-many-through polymorphic-associations