Очевидно, это распространенная ошибка. Однако я не могу решить эту проблему при просмотре моего кода. Я пытаюсь получить доступ к API ProPublica для конгресса. Моя модель, представление и контроллер довольно просты, и именно этот код работал со мной при доступе к 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
Мой взгляд:
<% @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
, разве вам не нужно его анализировать? - person Sebastian Palma   schedule 16.07.2017<%= debug @response %>
в представление и проверить структуру ответа, и оттуда, если она отключена, вы сможете отследить, что изменилось или почему это отличается от того, что вы ожидаете оттуда - person Simple Lime   schedule 16.07.2017<%= @response.parsed_response %>
и рассказать нам, что оно отображает. - person Lasse Sviland   schedule 17.07.2017