【发布时间】:2017-07-23 21:22:40
【问题描述】:
我正在使用 HTTParty gem、Rails 5 和“httplog” gem。
我使用“httplog”gem 跟踪了我的 HTTP 请求,并收到了正确的 JSON 响应。因此,我认为我的问题正在发生。我正在从模型中正确访问 API。我根据 HTTP 日志在控制器中正确使用它。我只是在我的视图和控制器之间的某个地方搞砸了。
我在访问 API 时收到 “undefined method `each' for nil:NilClass” 错误。
这是来自 API 的示例响应:
{
"result_count": 8132,
"page_size": 250,
"current_page": 1,
"total_pages": 33,
"api_call_credits": 1,
"data": [
{
"ticker": "A",
"name": "Agilent Technologies Inc",
"lei": "QUIX8Y7A2WP0XRMW7G29",
"cik": "0001090872",
"latest_filing_date": "2017-02-06"
}
这是我的模型:
class Finance < ApplicationRecord
include HTTParty
def self.response
auth = {
username: "username",
password: "password"
}
options = { basic_auth: auth }
data_url = "https://api.intrinio.com/companies?ticker=AAPL"
HTTParty.get(data_url, options)
end
end
我的控制器:
class FinancesController < ApplicationController
def index
@response = Finance.response
end
end
我的观点:
<% @response["data"].each do |data| %>
<p><%= data["name"]%></p>
<p><%= data["ticker"]%></p>
<% end %>
【问题讨论】:
标签: ruby-on-rails http ruby-on-rails-5 httparty