我在 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
因此,基本上,食谱的成分行可以包含另一个食谱或食品表中的元素(每个食谱可以包含任意数量的成分行)。
这是一张代表我想要的图:
这是当前 RubyMine 中架构的样子:
问题是成分行(即父表)中的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_type
和 element_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/