Tom Hammond
Tom Hammond

Reputation: 6090

Rails access hash value

I'm playing around with Netflix's Workflowable gem. Right now I'm working on making a custom action where the user can choose choices.

I end up pulling {"id":1,"value":"High"} out with @options[:priority][:value]

What I want to do is get the id value of 1. Any idea how to pull that out? I tried @options[:priority][:value][:id] but that seems to through an error.

Here's what the action looks like/how I'm logging the value:

class Workflowable::Actions::UpdateStatusAction < Workflowable::Actions::Action
  include ERB::Util
  include Rails.application.routes.url_helpers

  NAME="Update Status Action"
  OPTIONS = {
      :priority => {
        :description=>"Enter priority to set result to",
        :required=>true,
        :type=>:choice,
        :choices=>[{id: 1, value: "High"} ]
      }
    }

  def run
    Rails.logger.debug @options[:priority][:value]
  end

end

Here's the error:

Error (3a7b2168-6f24-4837-9221-376b98e6e887): TypeError  in ResultsController#flag
no implicit conversion of Symbol into Integer

Here's what @options[:priority] looks like:

{"description"=>"Enter priority to set result to", "required"=>true, "type"=>:choice, "choices"=>[{"id"=>1, "value"=>"High"}], "value"=>"{\"id\":1,\"value\":\"High\"}", "user_specified"=>true}

Upvotes: 2

Views: 12907

Answers (2)

Frederick Cheung
Frederick Cheung

Reputation: 84182

@options[:priority]["value"] looks to be a strong containing json, not a hash. This is why you get an error when using [:id] (this method doesn't accept symbols) and why ["id"] returns the string "id".

You'll need to parse it first, for example with JSON.parse, at which point you'll have a hash which you should be able to access as normal. By default the keys will be strings so you'll need

JSON.parse(value)["id"]

Upvotes: 5

Rob Di Marco
Rob Di Marco

Reputation: 45002

I'm assuming the error is something like TypeError: no implicit conversion of Symbol into Integer

It looks like @options[:priority] is a hash with keys :id and :value. So you would want to use @options[:priority][:id] (lose the :value that returns the string).

Upvotes: 0

Related Questions