代码之家  ›  专栏  ›  技术社区  ›  T. Cole

在Rails中使用API时,nil:NilClass的未定义方法“each”

  •  0
  • T. Cole  · 技术社区  · 7 年前

    这显然是一个常见错误。然而,我在检查代码时无法解决这个问题。我正在为国会访问ProPublica的API。我的模型、视图和控制器非常简单,在访问谷歌新闻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'
    

    {
       "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 回复  |  直到 7 年前
        1
  •  1
  •   Lasse Sviland    7 年前

    你得到 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 %>