0

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

ROR 代码

Class.where(challenge_id:challenge.id,song_id:song_hash['song_id']).first

错误是_

can't convert String into Integer

我什至将其更改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"}}}}

找不到未转换为整数的内容

4

3 回答 3

7

我猜你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"}],

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

>> song_hash = [ ]
>> song_hash['song_id']
TypeError: can't convert String into Integer

您的代码中唯一的索引是:

song_hash['song_id']

这肯定是用字符串索引的东西,因此它与您看到的 TypeError 匹配。将其更改为:

song_hash['song_id'].to_i

不会有帮助,因为在有机会做任何事情[]之前会调用有问题的方法。to_i

于 2013-09-23T06:12:13.323 回答
0

可能您的任何字段(challenge_idsong_id)都是整数,但是您在 json 中也插入了一个字符串,有很多模棱两可的东西无法理解challenge_id":cId是整数

根据你的

对于所有歌曲 ID

      irb(main):016:0* song_hash = {"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"}}}

      => {"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"}}}


      irb(main):018:0> song_hash["guessed_songs"].each do |key,song|
      irb(main):019:1* puts song["song_id"].to_i
      irb(main):020:1> end
      =>10
      =>11
      =>12
      =>13
      =>15
      => {"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"}}

所以在循环中你可以试试这个

           pm=PlaylistMembership.where(challenge_id:challenge.id,song_id:song["song_id"].to_i).first
于 2013-09-23T05:55:43.143 回答
0

尝试这个:

song_id:song_hash[:song_id]

于 2013-09-23T05:57:29.993 回答