【发布时间】:2017-07-16 20:23:44
【问题描述】:
这显然是一个常见错误。但是,在查看我的代码时,我无法解决这个问题。我正在尝试访问 ProPublica 的国会 API。我的模型、视图和控制器非常简单,并且在访问 Google 新闻 API 时,这个确切的代码对我有效。
当我尝试在视图中使用“.each”方法迭代 JSON 响应时,我不断收到未定义的方法错误。我相信我会根据 API 的请求将正确的标头传递给它。
我的模型:
class CongressTracker < ApplicationRecord
include HTTParty
def self.response
#congress = "most recent congress"
#chamber = "one each for congress and senate"
#type = "introduced, passed, etc."
congress_url = "https://api.propublica.org/congress/v1/115/senate/bills/passed.json"
HTTParty.get(congress_url,
:headers => {
"X-API-KEY" => "api-key-here"
})
end
end
class Bill < ApplicationRecord
include HTTParty
end
我的控制器:
class BillsController < ApplicationController
def index
@response = CongressTracker.response
end
end
我的看法:
<% @response["results"].each do |bill| %>
<p><%= bill["title"]%></p>
<p><%= bill["summary"]%></p>
<% end %>
我的路线:
resources :bills
详细错误:
Rendering bills/index.html.erb within layouts/application
Rendered bills/index.html.erb within layouts/application (2.0ms)
Completed 500 Internal Server Error in 312ms (ActiveRecord: 0.0ms)
ActionView::Template::Error (undefined method `each' for nil:NilClass):
1: <% @response["results"].each do |bill| %>
2: <p><%= bill["title"]%></p>
3: <p><%= bill["summary"]%></p>
4: <% end %>
app/views/bills/index.html.erb:1:in `_app_views_bills_index_html_erb__2110131784793159686_70138696839360'
预期的 JSON 响应示例(我可以在终端中工作):
{
"status":"OK",
"copyright":"Copyright (c) 2017 Pro Publica Inc. All Rights Reserved.",
"results":[
{
"congress": "115",
"chamber": "Senate",
"num_results": "20",
"offset": "0",
"bills": [
{
"bill_id": "hr2825-115",
"bill_type": "hr",
"number": "H.R.2825",
"bill_uri": "https://api.propublica.org/congress/v1/115/bills/hr2825.json",
"title": "DHS Authorization Act of 2017",
"summary": "",
},
【问题讨论】:
-
@response的内容是什么,不用解析吗? -
我相信 HTTParty 有它自己的解析 JSON 的方式。这个确切的代码适用于我也在使用的 Google News API,所以我认为解析 JSON 响应不是问题。
-
您可以尝试的一件事是将
<%= debug @response %>扔到视图中并验证响应结构,如果它关闭,您可以从那里追踪更改的内容或为什么它与您的不同'从那里重新期待 -
很遗憾,尝试调试并没有给我任何额外的信息。
-
您能否将您的视图内容替换为
<%= @response.parsed_response %>,并告诉我们它呈现的内容。
标签: ruby-on-rails json http ruby-on-rails-5 httparty