Question

I am designing an API with Rails 4, and right now I have the following for the create action of my Orders controller:

def create
    begin
      @order = @api_user.orders.create!(order_params)
      render :json => @order, :only => [:id], :status => :created, :location => @order
    rescue
      render :json => {}, :status => :unprocessable_entity
    end
  end

With this, I ask the user to send a JSON that looks like this:

{"order" : {"description_1" : "Neque porro quisquam", "description_2" : "Neque porro quisquam", "types_attributes" : [{"url" : "http://test.com"}]}}

So, all I do to check the params is:

params.require(:order).permit(:description_1, :description_2, {types_attributes: [:url]})

My question is:

If I want to avoid the user to have to specify the "order" key in the JSON params, how would I call the create action? Would I need to do orders.create!(key1: params[:key1],...)?

What is the common approach to solve this?

Was it helpful?

Solution

If the params contains the attributes for an Order, then you just need to use:

@order = @api_user.orders.create!(params)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top