【问题标题】:ActiveRecord associations, has_many_throughActiveRecord 关联,has_many_through
【发布时间】: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


    【解决方案1】:

    :has_many through 方法在一个对象可以连接零个或多个其他对象时效果最佳&每个连接都有一些属性

    例如,在您的情况下,您将在Connections 表中存储每种成分的数量以及配方_id 和成分_id。

    所以,对我来说它看起来不错。 :)

    但是,您应该考虑将Ingredient_Recipe 表命名为更合适的名称。

    【讨论】:

    • 更合适的名字是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多