Rails访问哈希值
我正在玩Netflix的Workflowable gem。 现在我正在制作一个自定义动作,用户可以选择。
我最终用@options[:priority][:value]
拉出{"id":1,"value":"High"}
我想要做的是获取id值1.任何想法如何把它拉出来? 我试过@options[:priority][:value][:id]
但这似乎是错误的。
这是动作的样子/我如何记录值:
class Workflowable::Actions::UpdateStatusAction { :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
这是错误:
Error (3a7b2168-6f24-4837-9221-376b98e6e887): TypeError in ResultsController#flag no implicit conversion of Symbol into Integer
这是@options[:priority]
样子:
{"description"=>"Enter priority to set result to", "required"=>true, "type"=>:choice, "choices"=>[{"id"=>1, "value"=>"High"}], "value"=>"{\"id\":1,\"value\":\"High\"}", "user_specified"=>true}
@options[:priority]["value"]
看起来是一个强大的包含json,而不是哈希。 这就是使用[:id]
时出错的原因(此方法不接受符号)以及为什么["id"]
返回字符串“id”。
您需要先解析它,例如使用JSON.parse
,此时您将拥有一个您应该能够正常访问的哈希。 默认情况下,键将是字符串,因此您需要
JSON.parse(值)[ “ID”]
我假设错误类似于TypeError: no implicit conversion of Symbol into Integer
看起来@options[:priority]
是一个带键的哈希:id
和:value
。 所以你想要使用@options[:priority][:id]
(丢失:value
返回字符串的:value
)。