未定义的方法`每个' for nil:在Rails中使用API​​时的NilClass

时间:2017-07-16 20:23:44

标签: ruby-on-rails json http ruby-on-rails-5 httparty

这显然是一个常见的错误。但是,在查看代码时,我无法解决此问题。我正在尝试访问ProPublica的API进行大会。我的模型,视图和控制器非常简单,这个确切的代码在访问Google News 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 

我的观点:

&#13;
&#13;
<% @response["results"].each do |bill| %>
      <p><%= bill["title"]%></p>
      <p><%= bill["summary"]%></p>
  <% end %>
&#13;
&#13;
&#13;

我的路线:

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": "",
              },

1 个答案:

答案 0 :(得分:1)

您收到undefined method 'each' for nil:NilClass错误的原因很可能是因为响应为{"message"=>"Forbidden"},因为您的API密钥不正确。

我测试了您的代码,只要您拥有正确的API密钥,一切都能正常运行。

您的观点存在一些错误,很可能是因为您还没有结果。

要获得账单的标题和摘要,您需要这样的内容:

<% @response["results"].each do |result| %>
  <% result["bills"].each do |bill| %>
    <p><%= bill["title"]%></p>
    <p><%= bill["summary"]%></p>
  <% end %>
<% end %>