Roger
Roger

Reputation: 51

Rails, sending json params

I have to use an API that wants a single param 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've searched and read the documentation, I can't seems to find a way how to do this. I've searched with form_for or form_tag function and this seems not possible. I've tried both approach using remote => true, but it does not do what I want.

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

Is there any ways to do this?

Thank you

Upvotes: 4

Views: 242

Answers (3)

Ahmed Samir Shahin
Ahmed Samir Shahin

Reputation: 558

You can still send the data as json string :

  • In your jquery ajax setup, set contentType option to "text/html"

Upvotes: 0

hdgarrood
hdgarrood

Reputation: 2151

I think Rails might automatically be turning the parameter into a hash, since it recognises that it's json. You should be able to turn it back into a string by calling to_json on it.

Upvotes: 0

oshikryu
oshikryu

Reputation: 249

Try accessing the json object as so

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

The [0] was included to read the first element of the json formatted object, assuming it isn't nested within another json object.

Upvotes: 1

Related Questions