0

I am JSON posting the following JSON to my controller:

{"user_id": 234324, "user_action": 2, "updated_email": "asdf@asdf.com" }

In my controller I can see the JSON is correctly POSTED but I am not sure how to access it:

def update_email
  puts request.body.read.html_safe

  user_id = params[:user_id]
  user = User.find(user_id)
end

I am testing this in my controller_spec and currently it is throwing an exception and is showing the id is empty.

Blankman
  • 259,732
  • 324
  • 769
  • 1,199

2 Answers2

0

This may be a duplicate - see: How do I parse JSON with Ruby on Rails?

I'm not sure how you're passing the JSON. Is it part of the POST params? In the header? Or something else. My guess is that you're either passing it as a param or should do so: e.g. myJson = {"user_id": 234324, "user_action": 2, "updated_email": "asdf@asdf.com" }

As far as parsing it goes, you should be able to use the built-in JSON class for this.

hash = JSON.parse params["myJson"]
Community
  • 1
  • 1
Richard
  • 11
  • 2
  • I'm just confused, when you post the json ```{"user_id": 234324, "user_action": 2, "updated_email": "asdf@asdf.com" }``` how can you access it using params["myJson"] ? there is no myJson in the JSON?? Is myJson just arbitrary? – Blankman Jul 18 '16 at 15:31
  • It's meant to represent however you're passing the information. Are you sending this JSON through an AJAX call as a param? What are you referring to by saying you're "JSON posting?" Could you add the code that's sending the POST to the controller - that may help. – Richard Jul 18 '16 at 15:46
0

Accessing it with params is the right way.

In your case:

params["user_id"] # => 234324

request.body.read shouldn't be used in real world, just for debugging, as action_dispatch does all the dispatch for you (like parse JSON or form data).

Note: you need to have the correct headers set, to let rails know that you're passing JSON.

siegy22
  • 4,295
  • 3
  • 25
  • 43