我有以下模型
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字段转换为模型,但我的模型是Address,而不是billing_address。
有没有告诉params使用Address而不是BillingAddress。如果没有,那么实现这种嵌套保存的最佳替代方法是什么?
答案 0 :(得分:1)
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_name:embeds_one :billing_address, as: :addressable, class_name: "Address"