0

I have an rails app with json api. So far I can create single objects via POST request.

It's fairly simple:

def create
    customer = Customer.new(customer_params)
    if customer.save
        render json: customer, status: 201
    else
        render json: customer.errors, status: 422
    end
end

and:

private
        def customer_params 
            params.require(:customer).permit(:name, :city)
        end

Now I want to create multiple customers by passing an array in my http request. Like this:

{
"customer": [
    {
        "name": "foo",
        "city": "New York"
    },
    {
        "name": "bar",
        "city": "Chicago"
     }
  ]
}

However, I don't know how to approach this. The first issue is that my strong parameters function doesn't accept arrays. Is there a way to use strong parameters and let me loop through the array?

potofski
  • 101
  • 1
  • 3
  • 12

1 Answers1

2

I would see it as a new controller method

something like:

def multi_create
  render json: customer.errors, status: 422 and return unless params[:customers]
  all_created = true
  customers = []
  params[:customers].each do |customer_params|
    customer = Customer.create(name: customer_params[:name], city: customer_params[:city])
    customers << customer
    all_created &&= customer.valid?
  end

  if all_created
    render json: customers, status: 201
  else
    render json: customers.map(&:errors), status: 422
  end 
end

You also need to add the route. then you could post your json to that route with the change that the outermost key should be customers.

I would not run this code without any changes but you get the general idea. And you can refactor it to your liking.

Albin
  • 2,912
  • 1
  • 21
  • 31
  • This is more or less correct (depending of the use case), however needs additional handler (e.g `transaction`) in case of failure of adding any customer. Now, if any failures, all remaining stay in the database. – blelump Mar 16 '15 at 10:56
  • I agree. Most of all it needs some decisions on how to handle requests where one or more creations fail. If you want to rollback everything or what you want to achieve. That was more or less what I meant with my last line about changes... – Albin Mar 16 '15 at 10:59