【问题标题】:Rails: has_many with extra details?Rails:has_many 有额外的细节吗?
【发布时间】:2011-01-06 22:10:56
【问题描述】:

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

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

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

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

如果我们只想将食谱与成分相关联,只需添加适当的 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

【问题讨论】:

    标签: ruby-on-rails activerecord has-many has-many-through


    【解决方案1】:

    Recipes 和 Ingredients 具有 has 和 belongs to 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 添加验证,以确保每种成分在每个配方中列出一次,并添加一个回调以将重复项合并到一个条目中。

    【讨论】:

    • 谢谢。这就是我所希望的信息!你能解释一下吗?为什么连接模型 RecipeIngredients 使用“belongs_to”而不是“has_one”?
    • 简短版本是连接模型的工作方式。长版本是,关系的每一边都必须有一个 belongs_to 和一个 has_one/has_many 边。属于另一个模型的模型必须具有外键 (other_model_id) 才能将其链接到另一个模型的实例。 Belongs_to 通常表示依赖关系。在您的情况下,RecipeIngredient 没有任何意义,除非它属于食谱和成分。成分和食谱在没有链接到食谱成分的情况下有意义。
    【解决方案2】:

    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. class Ingredient(属于recipe,有很多componentrecipecounts)
    2. 类食谱(有很多成分,有很多成分食谱计数)
    3. class IngredientRecipeCount(属于配料,属于配方)

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

    【讨论】:

    • has_and_belongs_to_many 在过去的一年里基本上被经验丰富的 Rails 开发人员视为已弃用(支持 has_many => :though)。
    • 是的!随着 Rails 3.1 的出现,它正在消亡。我认为这可能是一件好事。值得庆幸的是,另一个答案比我的要好得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多