I'm passing as array of JSON object as a param in Rails through an AJAX post/delete, like
[{'id': 3, 'status': true}, {'id': 1, 'status': true}]
How do I loop through the params[:list]
to get each id and status value?
I'm passing as array of JSON object as a param in Rails through an AJAX post/delete, like
[{'id': 3, 'status': true}, {'id': 1, 'status': true}]
How do I loop through the params[:list]
to get each id and status value?
Try like follows:
params[ :list ][ 0 ][ :id ] # => 3, ...
params[ :list ].each {| v | v[ :id ] } # => 3, 1
In case if your hash is like ["0", {"id"=>"9", "status"=>"true"}]
:
# a = ["0", {"id"=>"9", "status"=>"true"}]
h = Hash[[a]]
# => {"0"=>{"id"=>"9", "status"=>"true"}}
and access to it will be:
h['0'][ :id ] # => '9'
Do this:
params[:list].each do |hash|
hash['id'] # => 3
hash['status'] # => true
end
There were two steps to this, plus what @Agis suggested. (Thanks @Agis)
I had to first stringify the JSON:
'p': JSON.stringify(p),
So that it does not create that wierd array. There was another stackoverflow answer using this method to generate a correct data JSON object, but it was encapsulating the whole data... I need to have this on just p
and not affect 'stringifying' the security token.
Understood this from here: Rails not decoding JSON from jQuery correctly (array becoming a hash with integer keys)
Next, I had to decode just that param, using
ActiveSupport::JSON.decode(params[:p])
a clue from here: How do I parse JSON with Ruby on Rails?
Lastly, can I then use the loop and access item['id']
Here's a loop:
params[:list].each do |item|
item.id
item.satus
end
If you want to create an array of id
's or something:
list_ids = params[:list].map(&:id)