Chris.Zou
Chris.Zou

Reputation: 4596

Posting a json array to rails server

I want to know how can I post json array directly to rails server. Say,

POST '/api/notes_bulk', HTTP/1.1
Content-Type: application/json

[{“content”:”content1”, “title”:”title1”}, {“content”:”content2”, “title”:”title2”}, {“content”:”content3”, “title”:”title3”}, {“content”:”content4”, “title”:”title4”}, {“content”:”content5”, “title”:”title5”}]

I did some search about it and all of the examples had some kind of key mapped to the array. While in my case, the json is an array at its top level. How can I get the json data in the controller code? I notice that rails wraps this data with a "_json" key, but when I accessing it, it says
Unpermitted parameters: _json, ....

Upvotes: 7

Views: 5545

Answers (4)

shev.vadim.net
shev.vadim.net

Reputation: 81

You can use that '_json' key to access data. To remove the warning you have to permit all the object keys from JSON array. In your case:

params.permit(_json: [:content, :title])

Upvotes: 6

Joost Baaij
Joost Baaij

Reputation: 7608

You cannot use the built-in params from Rails in this case but you can create your own parser:

def create
  contents = JSON.parse(request.raw_post)
end

The contents variable will be the array that you posted.

Upvotes: 2

Eugene
Eugene

Reputation: 647

I think this might be late, but just post here since the question is unanswered and for future visitors.

You have to wrap you JSON string into an object. For example, you can construct you Json string such as

var contentArray = [{“content”:”content1”, “title”:”title1”}, {“content”:”content2”, “title”:”title2”}];
var contentObj = {contents: contentArray};

Before submiting it to Rails

jsonData = JSON.stringify(contentObj);

Access it in Rails controller:

myContentArray = params[:contents]

Upvotes: 0

Atul
Atul

Reputation: 268

i think the issue you are facing had got to do with strong parameters. you need to allow json params in controller. Use params.require(:object).permit( list of allowed params)

Upvotes: 0

Related Questions