通过 accepts_nested_attributes_for 构建的多态 has_one 未设置多态类型

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

我从这个 class 继承来创建我自己的计算器,它看起来很像(与任何其他 Spree Calculator subclass 略有不同):

module Spree
  class Calculator
    class PercentDiscountOnVariant < Calculator
      preference :percent, :decimal, default: 0

      ...
    end
  end
end

我的模型,名为 ClientProductCalculatorhas_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(新记录或更新现有记录)时,calculable_typecalculators table 保持为空。 但是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_ids 和 client_ids 大量插入多个 ClientProduct 行。但是,calculator_attributes 对于每个创建的 ClientProduct 都是相同的,所以我认为这个特定的设置不会改变任何东西。但是,如果有人觉得这可能相关,请告诉我,我会提供实际的(虽然更长)代码。

不确定这是否是原因,但您在关系的另一端遗漏了多态部分( the has one side )

has_one :calculator,
  inverse_of: :calculable,
  foreign_key: :calculable_id,
  dependent: :destroy,
  as: :calculable        #  <== this part