ruby grape post method insert multiple rows

315 Views Asked by At

How to post multiple rows into DB using ruby Grape. For example when testing with CURL this is working fine

curl -H "Content-Type: application/json" -X POST \
     -d '{"name": "test", "age": "22"}' http://localhost:3000/students

But this is not working

curl -H "Content-Type: application/json" -X POST \
     -d '[{"name": "test", "age": "22"}, {"name": "someone", "age": "32" }]' \
     http://localhost:3000/students

This is my grape api code

post do
      student = Student.new
      student.name = params[:name]
      student.age = params[:age]
      student.save!
end
1

There are 1 best solutions below

1
On

You use a bad syntax for JSON array object. Try this:

curl -H "Content-Type: application/json" \
     -X POST \
     -d '[{"name": "test", "age": "22"}, {"name": "someone", "age": "32" }]' \
     http://localhost:3000/students

EDIT :

If your payload is {"name": "test", "age": "22"} your code works. But you have a Array (params.kind_of?(Array)).

You can make this:

post do
  params.each do |student_params|
    student = Student.new
    student.name = student_params[:name]
    student.age = student_params[:age]
    student.save!
  end
end

Explanation:

params[:name]
# => nil
params.first[:name]
#=> test