calyxofheld
calyxofheld

Reputation: 2128

accessing params in actioncontroller hash but getting undefined method

I would like to access the params hash with params["uppyResult"][0]["successful"][0]["id"], but this results in undefined method '[]' for nil:NilClass.

My params are going through a POST request like this:

Parameters: 
 {"utf8"=>"✓", "authenticity_token"=>"[FILTERED]", 
  "item"=>{
   "title"=>"90", 
   "info"=>"90", 
  }, 
  "commit"=>"Next", 
  "uppyResult"=>"[
   { "successful":[
    {"id":"uppy-e6drjvpxoaikvhf/jpeg-1e-image/jpeg-153049-1626052105955","name":"E6DrJVPXoAIKVhf.jpeg"
    }
   ]}
  ]
 }

Testing up the params to see where I went wrong, puts params["uppyResult"] puts exactly what I would expect, whereas puts params["uppyResult"][0] puts just [. Everything after that is an undefined method. Where am I going wrong?

Upvotes: 1

Views: 719

Answers (1)

Christian Bruckmayer
Christian Bruckmayer

Reputation: 2187

The content in uppderResult is a string and not array. That is why you get only [.

I believe the content is JSON encoded so you could just parse it to get an array.

JSON.parse(params["uppyResult"])[0]["successful"][0]["id"],

Please note that this code can still throw errors in production e.g. when malformed or nil. So you should implement make sure each element exist by e.g. using dig, first, parsing or & safe navigator.

A slightly more safe way to do it

def id
  successful_result[0].to_h['id']
end

def successful_result
  upper_result[0].to_h['successful'].to_a
end

def upper_result
  JSON.parse(params["uppyResult"])
rescue
  [] # rescue malformed JSON
end

Upvotes: 4

Related Questions