database - 与另一个模型或父模型的多态关联

标签 database ruby-on-rails-3 activerecord polymorphism models

我在 Rails 中有一个名为 Recipe 的模型。配方模型包含成分。每个成分系列都与食品模型或另一个配方相关联。所以基本上我想要一个与食物模型和食谱模型的多态关联。然而,当我进行更改时,成分类中的recipe_id始终为空。关联中是否存在明显的错误?

class Recipe < ActiveRecord::Base
  has_many :ingredients, :as => :element
end

class Food < ActiveRecord::Base
  has_many :ingredients, :as => :element
  has_many :recipes, :through => :ingredients
end

class Ingredient < ActiveRecord::Base
  belongs_to :element, :polymorphic => true
  belongs_to :recipe
end

因此,基本上,食谱的成分行可以包含另一个食谱或食品表中的元素(每个食谱可以包含任意数量的成分行)。

这是一张代表我想要的图:

Drawing of tables

这是当前 RubyMine 中架构的样子:

Rubymine diagram

问题是成分行(即父表)中的recipe_id 现在为空,因此当我开始实现多态关联时,该关系已停止工作。

以下是我保存菜谱时的插入行:

  SQL (3.4ms)  INSERT INTO "recipes" ("created_at", "description", "directions", "name", "owner", "recipe_source_type_id", "servings", "source", "time", "updated_at", "visibility") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING "id"  [["created_at", Sun, 10 Jun 2012 13:43:12 UTC +00:00], ["description", "Þetta er önnur prufuuppskrift"], ["directions", "Já, og leiðbeiningar"], ["name", "Prufuuppskrift II"], ["owner", 1], ["recipe_source_type_id", 1], ["servings", 3], ["source", "aaa"], ["time", 3], ["updated_at", Sun, 10 Jun 2012 13:43:12 UTC +00:00], ["visibility", 0]]
  SQL (0.9ms)  INSERT INTO "ingredients" ("created_at", "description", "element_id", "element_type", "order", "qty", "recipe_id", "unit_type_id", "updated_at", "user_entered_qty") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING "id"  [["created_at", Sun, 10 Jun 2012 13:43:13 UTC +00:00], ["description", "abc"], ["element_id", 9], ["element_type", "Recipe"], ["order", nil], ["qty", 2.0], ["recipe_id", nil], ["unit_type_id", 1], ["updated_at", Sun, 10 Jun 2012 13:43:13 UTC +00:00], ["user_entered_qty", "2 gramm"]]

我稍后要解决的另一个问题是,在本例中,element_type 应该是 Food 而不是 Recipe。我不知道在哪里设置。

最佳答案

据我了解,一种成分既可以属于食物,也可以属于食谱。如果是这种情况,那么您的多态关联 Element 将处理该问题。

它将在您的 Ingredients 表中创建 2 个字段,一个称为 element_typeelement_id,其中 element_type 将包含与其相关的表,element_id 将包含 element_type 引用的表中记录的 ID。

这会使您的belongs_to :recipe变得多余。事实上,当您将成分分配给配方时,Rails 会为您填充“多态字段”,而不是填充recipe_id,因为您已经告诉它通过设置 :polymorphic => true< 来填充多态字段.

我希望这能解释你的困境。请记住我告诉你的内容,观看此 RailsCast on Polymorphic Associations ,事情应该就清楚了。

希望我能有所帮助。

关于database - 与另一个模型或父模型的多态关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10961930/

相关文章:

ruby-on-rails - 语法错误,意外的 ':',期望使用Rails 3以Stripe形式出现 ')'

ruby-on-rails - Rails 对象在当前返回 false?但是 !nil 是真的吗?

php - 如何在codeigniter中将mysql数据库的多个表作为单个表进行查询(获取)

MySQL 在选择时无法识别字符 '?'

ruby-on-rails-3 - 如何在 Rails 中将字符串变形为模型名称?

mysql - MongoDB: map /单位为浏览器游戏中的模型设计提供建议

ruby - 扩展 ActiveSupport::Notifications.subscribe, instantiation.active_record 钩子(Hook)

activerecord - 使用 ElasticSearch 和 Tire 过滤关联 ID

mysql - 使用来自不同社交网络的数据实现新闻源

mysql - 无法通过命令行连接本地MySQL数据库?