Rails sending json params

I need to use an API that wants to have one parameter containing a json string:

def function data = params['data'] # Do thing with the json string data #... More code end 

config.rb:

 match "/thing" => "controller#function", :via => :post 

I searched and read the documentation, I can not find a way to do this. I was looking for a form_for or form_tag function and this seems impossible. I tried both approaches using remote => true, but it does not do what I want.

I also tried to do this using jquery $ .ajax, but it sends the parameters in json format, not the json string.

Are there any ways to do this?

thanks

+4
source share
3 answers

Try to access the json object like this

 data = params[:data].first[0] 

[0] was enabled to read the first element of a json-formatted object, assuming that it was not nested in another json object.

+1
source

I think Rails can automatically turn a parameter into a hash, since it recognizes it as json. You must return it back to the string by typing to_json .

0
source

You can still send data as a json string:

  • In jQuery ajax setup, set contentType to "text / html"
0
source

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


All Articles