2017-06-02 56 views
0

我有型号如下PARAMS需要嵌套属性为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到/客户

里面我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。如果没有,那么实现这种嵌套保存的最佳选择是什么?

回答

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"

+0

我不知道如何帮助,我现在需要在我的JSON输入billing_address_attributes为好,并在此之后,它给出了同样的错误。 – Tommy

+0

看到你的编辑,添加class_name到模型的工作。谢谢! – Tommy