Tommy
Tommy

Reputation: 27

Params require on nested attributes for mongoid

I have models as below

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

I want to be able to save the billing address and shipping address directly with 1 POST to /customer

Inside my CustomerController I have the following

   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

Right now everytime I run this, it gives the error uninitialized constant BillingAddress

params seems to be trying to convert the billing_address field into a model, but my model is Address, not billing_address.

Is there anyway to tell params to use Address rather than BillingAddress. If not, what's the best alternative to implementing this nested save?

Upvotes: 0

Views: 131

Answers (1)

wesley6j
wesley6j

Reputation: 1403

billing_address should be 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

The uninitialized constant BillingAddress error is because it guesses class name from billing_address.

To fix this problem, add class_name : embeds_one :billing_address, as: :addressable, class_name: "Address"

Upvotes: 1

Related Questions