在视图中显示Json

时间:2015-04-03 00:15:03

标签: ruby-on-rails ruby json parsing

我试图在我的视图中显示来自json文件的信息时遇到问题。我已经解析了它。

这是我的错误:

When assigning attributes, you must pass a hash as an argument.
Extracted source (around line #23):

21 # @new_member.constructors = [driver['Constructors'][0]['name']]
22      # @new_member.points = [driver['points']]
23      @new_member.from_json(json)

        @members << @new_member
    end

        # @new_member.constructors = [driver['Constructors'][0]['name']]
        # @new_member.points = [driver['points']]
        @new_member.from_json(json)

        @members << @new_member
    end

这是我的控制者:

require 'open-uri'
require 'json'

url = "http://ergast.com/api/f1/2014/driverStandings.json"
data = JSON.parse(open(url).read)
standings = data['MRData']['StandingsTable']['StandingsLists'][0]['DriverStandings']

@members = Array.new
standings.each do |driver|
    json = standings.to_json
    @new_member = Member.new
    # @new_member.position = [driver['position']]
    # @new_member.givenName = [driver['Driver']['givenName']]
    # @new_member.familyName = [driver['Driver']['familyName']]
    # @new_member.constructors = [driver['Constructors'][0]['name']]
    # @new_member.points = [driver['points']]
    @new_member.from_json(json)

    @members << @new_member

如果我取消注释控制器中的行并删除这些行

@new_member.from_json(json)
json = standings.to_json

我在视图中得到以下内容

姓名:[“刘易斯”]

姓名:[“Nico”]

该视图非常接近,但不是我需要的,我需要没有[“”]的数据, 所以我需要的观点是:

<1>刘易斯汉密尔顿梅塞德斯384

提前致谢。

1 个答案:

答案 0 :(得分:0)

备选方案1

更改行:

@new_member.givenName = [driver['Driver']['givenName']]

成:

@new_member.givenName = driver['Driver']['givenName']

删除外部[],以便您填充的字段@new_member.givenName变为字符串而不是包含一个字符串的数组。

备选方案2

当循环遍历standings哈希时,driver临时变量是否可能是哈希?

在这种情况下,可能就足够了:

@members = Array.new standings.each do |driver| @members << Member.new(driver) end

Bonus:你可能不需要分配一个实例变量@new_member,它会在循环的每次迭代中被覆盖