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?

2
  • In params... it becomes ["0", {"id"=>"9", "status"=>"true"}] Commented Jan 29, 2014 at 9:46
  • Error: can't convert Symbol into Integer Commented Jan 29, 2014 at 9:51

4 Answers 4

0

Do this:

params[:list].each do |hash|
  hash['id'] # => 3
  hash['status'] # => true
end
Sign up to request clarification or add additional context in comments.

2 Comments

Wouldn't this loop through each item? I.E you don't need to loop through the hash variable?
Thanks, this is correct, the answer I've posted has this and also deals with the issue why this couldn't work beforehand.
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'

2 Comments

@bcm dump the params[ :list ][ 0 ].inspect
Thanks, I've posted the answer which deals with the root problem.
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']

Comments

-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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.