Posting json array to rails server

I want to know how to send json array directly to rails server. Let's 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 a few searches, and in all the examples there was some kind of key mapped to an array. Although in my case json is an array at its top level. How can I get json data in controller code? I notice that the rails wrap this data with the "_json" key, but when I access it, it says that Unpermitted parameters: _json, ....

+4
source share
4 answers

In this case, you cannot use the built-in Rails parameters, but you can create your own parser:

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

The variable contentswill be the array you allocated.

+1

"_json" . , JSON. :

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

I think the problem you are facing is related to strong parameters. you need to enable json params in the controller. Use params.require (: object) .permit (list of allowed parameters)

0
source

I think it may be too late, but just post here, as the question remains unanswered for future visitors.

You must wrap the JSON string in an object. For example, you can build a Json string, for example

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

Before submitting to Rails

jsonData = JSON.stringify(contentObj);

Access it in the Rails controller:

myContentArray = params[:contents]
0
source

Source: https://habr.com/ru/post/1598484/


All Articles