[英]accepts_nested_attributes_for with has_many polymorphic
[英]Polymorphic has_one built through accepts_nested_attributes_for is not setting polymorphic type
注意:雖然該項目使用的是Spree 2.3版,但我目前不認為這是Spree特有的問題。 如果我錯了,請糾正我。
Spree框架有一個稱為Calculator
的模型,如下所示:
module Spree
class Calculator < Spree::Base
belongs_to :calculable, polymorphic: true
...
end
end
我從此類繼承而來,創建了自己的計算器,看起來就像(與其他Spree Calculator子類幾乎沒有什么不同):
module Spree
class Calculator
class PercentDiscountOnVariant < Calculator
preference :percent, :decimal, default: 0
...
end
end
end
我的模型ClientProduct
與Calculator
具有has_one
關系,並且可以接受嵌套的屬性,就像這樣:
module Spree
class ClientProduct < ActiveRecord::Base
has_one :calculator, inverse_of: :calculable, foreign_key: "calculable_id", dependent: :destroy
accepts_nested_attributes_for :calculator
...
end
end
問題是,當我創建ClientProduct
(新記錄或更新現有記錄)時, calculators
表中的calculable_type
列保持為空。 然而 , calculable_id
與正確填充ClientProduct
的ID。
參數圖的相關部分是:
"client_product"=>{
"variant_id"=>"300",
"client_id"=>"2",
"role_ids"=>["7"]
"calculator_attributes"=> {
"type"=>"Spree::Calculator::PercentDiscountOnVariant",
"preferred_percent"=>"15"
}
}
而ClientProduct
與簡單地創建Spree::ClientProduct.create(client_product_params)
是什么會導致正確設置多態ID,同時又使多態類型列為空?
較小的旁注:為簡潔起見,我在某種程度上撒謊了ClientProduct
的構建方式。 使用variant_id和client_id的組合,大量插入多個ClientProduct
行。 然而, calculator_attributes
對於每個相同ClientProduct
時創建的,所以我不相信這個特殊的設置改變任何東西。 但是,如果有人覺得這可能是相關的,請告訴我,我將提供實際的(盡管更長)代碼。
不知道這是否是原因,但您在關系的另一側(的一側)遺漏了多態部分
has_one :calculator,
inverse_of: :calculable,
foreign_key: :calculable_id,
dependent: :destroy,
as: :calculable # <== this part
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.