Reputation: 83
I have the following JSON params.
Started POST "/tickets/move.json" for ::1 at 2015-01-30 15:30:13 -0600
Processing by TicketsController#move as JSON
Parameters: {"_json"=>[{"id"=>"1", "col"=>1, "row"=>1}, {"id"=>"2", "col"=>2, "row"=>2}, {"id"=>"3", "col"=>2, "row"=>1}, {"id"=>"4", "col"=>4, "row"=>1}, {"id"=>"5", "col"=>5, "row"=>1}], "ticket"=>{}}
How can I access them, as I would with regular rails params?
Upvotes: 4
Views: 7661
Reputation: 106017
That's a regular params
hash. Rails is usually smart enough to decode a JSON request and put the resulting object in params
for you, and the hashrockets (=>
) are a dead giveaway that it's a Ruby hash and not JSON. Formatted more nicely it looks like this:
{ "_json" => [ { "id" => "1", "col" => 1, "row" => 1 },
{ "id" => "2", "col" => 2, "row" => 2 },
# ...
],
"ticket" => {}
}
You'll access it like any other Hash:
p params["_json"]
# => [ {"id"=>"1", "col"=>1, "row"=>1},
# {"id"=>"2", "col"=>2, "row"=>2},
# ...
# ]
p params["_json"][0]
# => {"id"=>"1", "col"=>1, "row"=>1}
p params["_json"][0]["id"]
# => "1"
p params["ticket"]
# => {}
It ought to be a HashWithIndifferentAccess, actually, so you should be able to use symbol keys as well:
p params[:_json][0][:id]
# => "1"
Upvotes: 11