【问题标题】:How do I access the parameters from json API in Rails? [closed]如何从 Rails 中的 json API 访问参数? [关闭]
【发布时间】:2018-01-16 22:47:07
【问题描述】:

我的 rails 应用程序正在从 json 接收以下内容。如何在 Ruby 中访问属性的名称键和日历 ID。

 Parameters: {"data"=>{"type"=>"user-events", "attributes"=>{"name"=>"An event", "location"=>"University of Illinois at Urbna-Champaign", "notes"=>"Testing my eventf\n", "all-day"=>false, "recurring"=>false, "sunday"=>false, "monday"=>false, "tuesday"=>false, "wednesday"=>false, "thursday"=>false, "friday"=>false, "saturday"=>false, "start-date"=>"01-16-2018", "stop-date"=>"01-16-2018", "start-time"=>"04:32PM", "stop-time"=>"05:32PM"}, "relationships"=>{"calendar"=>{"data"=>{"type"=>"calendars", "id"=>"685"}}}}}

我是否使用下面的代码来访问 name 属性?

 params[:data][:attributes][:name] 

另外,我是否使用以下内容来访问日历的 id ?

params[:data][:relationships][:calendar][:data][:id]

提前感谢您的帮助

【问题讨论】:

  • 在提出任何问题之前总是先尝试一下,如果它对你很好而且很好,如果没有,显示错误的输出或你得到的错误。
  • 是的,我觉得它看起来不错,所以在发布问题之前一定要尝试
  • 当我使用上述方法时,我得到 nil:NilClass 的未定义方法 `[]'

标签: ruby-on-rails json ruby api parameters


【解决方案1】:

如果你的哈希名称是参数

    Parameters['data']['attributes']['name'] # "An event" 
    Parameters['data']['relationships']['calendar']['data']['id'] # "685"

如果是参数,那么

    params['data']['attributes']['name'] # "An event" 
    params['data']['relationships']['calendar']['data']['id'] # "685"

将访问属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多