我在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行(這是父表)現在爲null,所以當我開始實現多態關聯時,關係停止工作。
這裏是插入線,當我保存配方:
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應該是食品,而不是配方在這種情況下。我不知道該在哪裏設置。
嗯......我想沒有人有任何解決這個:-( – gugguson