0

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?

1 Answer 1

0

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

@order = @api_user.orders.create!(params)
Sign up to request clarification or add additional context in comments.

4 Comments

But is the approach to go and check those params for possible bad formatting? Or should I just try to create it?
I would rely on your strong parameters settings and AR validations to do the checking on the data. If these fail (using create!), you will get an exception.
Say I want to let the user to give me the IDS of an association, obviously I need to get those ids and make sure they exist in the database. Then it makes sense to check the JSON right?
Yeah, that would be smart. I would do this via a custom validation though, so that the logic is consolidated into your model with the rest of the validations. You could check for the existence of associated ids and add to the errors hash (:base or association) if one of the ids is not valid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.