Ruby on Rails无法将String转换为Integer

Muh*_*man 0 ruby hash json ruby-on-rails

我将JSON数据发送到解析它的控制器.

ROR代码

Class.where(challenge_id:challenge.id,song_id:song_hash['song_id']).first
Run Code Online (Sandbox Code Playgroud)

错误

can't convert String into Integer
Run Code Online (Sandbox Code Playgroud)

我甚至改变song_id:song_hash['song_id']song_id:song_hash['song_id'].to_i,但没有奏效

散列数据

{"session_token"=>"Xt9toEzHI3bYXeJNkenyqg", "challenge"=>{"challenge_id"=>"15", "player_name"=>"usman", "guessed_songs"=>{"0"=>{"song_id"=>"10", "guessed"=>"YES"}, "1"=>{"song_id"=>"11", "guessed"=>"YES"}, "2"=>{"song_id"=>"12", "guessed"=>"YES"}, "3"=>{"song_id"=>"13", "guessed"=>"YES"}, "4"=>{"song_id"=>"15", "guessed"=>"YES"}}, "player_status"=>{"0"=>{"coins"=>"20", "points"=>"0", "player_name"=>"usman"}, "1"=>{"coins"=>"20", "points"=>"0", "player_name"=>"Usman"}}}}
Run Code Online (Sandbox Code Playgroud)

无法找到未转换为整数的内容

mu *_*ort 6

我猜你song_hash根本不是哈希,它是一个数组.可能来自传入数据的这个数组:

"guessed_songs":[{"song_id":1,"guessed":"YES"},{"song_id":2,"guessed":"YES"},{"song_id":3,"guessed":"YES"},{"song_id":4,"guessed":"YES"},{"song_id":5,"guessed":"YES"}],
Run Code Online (Sandbox Code Playgroud)

您看到的错误几乎总是尝试索引数组的结果,就好像它是一个哈希.例如:

>> song_hash = [ ]
>> song_hash['song_id']
TypeError: can't convert String into Integer
Run Code Online (Sandbox Code Playgroud)

代码中唯一的索引是:

song_hash['song_id']
Run Code Online (Sandbox Code Playgroud)

这肯定是用字符串索引的东西,所以它匹配你看到的TypeError.将其更改为:

song_hash['song_id'].to_i
Run Code Online (Sandbox Code Playgroud)

将无济于事,因为在有机会做任何事情[]之前,将会调用to_i有问题的方法.