chris P chris P - 5 months ago 16
JSON Question

I want to POST multiple entries at a time to my Rails API backend via JSON. How?

How can you post multiple entries at once time. For example

def create
@visit = Visit.new(user_params)
if @visit.save
respond_with(@visit)
else

end
end

private

def user_params
params.require(:visit).permit(:room_id, :date)
end


If this is your controller, and you send the following POST…

Content-Type = application/json


and

{
"visit":
{
"room_id": "7",
"date": "2014-05-06"
}
}


That will create 1 entry. How can you created say 3 entries at once? How do you write the JSON array of 3 visit entries, and how do you permit them properly in the controller?

Answer

You could do it by looping through the JSON hash you receive, saving each record as you go:

def create
    for visit in params[:visit] do
        new_visit = Visit.new(user_params)
        new_visit.save
    end
    redirect_to visits_path
end

private

def user_params
   params.require(:visit).permit(:room_id, :date) # => we'll need to fix this
end

The bottom line is that just because you're meant to send data in a specific way, doesn't mean you can't do it other ways. You can loop through passed params, allowing you to call the save method on each [:visit] param you pass

Comments