我在 Rails 中有一个名为 Recipe 的模型。配方模型包含成分。每个成分行都与食物模型或另一个食谱相关联。所以基本上我想要一个与 Food 模型和 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。我不确定在哪里设置。