7

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, ....

4 Answers 4

6

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])
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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)

1 Comment

The problem is that the the whole json was an array, there is no :object for me to pass into require.
0

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]

1 Comment

This is not a great answer. You should not have to make your api fit rails. Posting an array is very common. Not to mention that you may not be generating the post request, an 3rd party might be and Rails should be able to process it.

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.