0

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?

bcm
  • 5,470
  • 10
  • 59
  • 92

4 Answers4

0

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'
Малъ Скрылевъ
  • 16,187
  • 5
  • 56
  • 69
0

Do this:

params[:list].each do |hash|
  hash['id'] # => 3
  hash['status'] # => true
end
Agis
  • 32,639
  • 3
  • 73
  • 81
  • Wouldn't this loop through each item? I.E you don't need to loop through the `hash` variable? – Richard Peck Jan 29 '14 at 09:31
  • Thanks, this is correct, the answer I've posted has this and also deals with the issue why this couldn't work beforehand. – bcm Jan 30 '14 at 02:06
0

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']

Community
  • 1
  • 1
bcm
  • 5,470
  • 10
  • 59
  • 92
-1

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)
Richard Peck
  • 76,116
  • 9
  • 93
  • 147