参数需要 mongoid 的嵌套属性

Params require on nested attributes for mongoid

我有以下型号

class Customer
   include Mongoid::Document
   field :first_name, type: String
   field :last_name, type: String
   embeds_one :billing_address, as: :addressable
   embeds_one :shipping_address, as: :addressable
end

class Address
  include Mongoid::Document
  field :country, type: String
  field :province, type: String
  field :city, type: String
  embedded_in :addressable, polymorphic: true
end

我希望能够直接使用 1 POST 将账单地址和送货地址保存到 /customer

在我的 CustomerController 中,我有以下内容

   def create
      @customer = Customer.new(customer_params)
      if @customer.save
        render json: @customer, status: :created
      else
        render json: @customer.errors, status: :unprocessable_entity
      end
    end

   private
   def customer_params
      params.require(:customer).permit(:first_name, :last_name,
      :billing_address => [:country, :province, :city],
      :shipping_address => [:country, :province, :city])
   end

现在每次我 运行 这个,它都会给出错误 uninitialized constant BillingAddress

params 似乎试图将 billing_address 字段转换为模型,但我的模型是地址,而不是 billing_address。

有没有办法告诉参数使用地址而不是帐单地址。如果没有,实施此嵌套保存的最佳替代方案是什么?

billing_address 应该是 billing_address_attributes:

def customer_params
  params.require(:customer).permit(:first_name, :last_name,
  :billing_address_attributes => [:country, :province, :city],
  :shipping_address_attributes => [:country, :province, :city])
end

uninitialized constant BillingAddress 错误是因为它从 billing_address 猜测 class 名字。

要解决此问题,请添加 class_name:embeds_one :billing_address, as: :addressable, class_name: "Address"