【问题标题】:Showing HTTP response in Rails - undefined method `each' for nil:NilClass在 Rails 中显示 HTTP 响应 - nil:NilClass 的未定义方法“每个”
【发布时间】: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


    【解决方案1】:

    我从未使用过 HTTP 派对,但我没有看到您“返回”响应正文的任何​​地方,通常您需要类似的东西

    response = HTTParty.get(data_url, options)
    response.body # being this the actual json response
    

    如果可行,您可以直接这样做

    HTTParty.get(data_url, options).body
    

    【讨论】:

    • 我可以试试。在访问许多其他 API 时,我如上所述使用这个 gem,它通常运行良好。我相信 HTTParty 有自己的自动解析 JSON 的方法。
    • 您可以随时打印@result 看看发生了什么?
    • 您能否举例说明如何正确使用“@result”来查找错误?
    • @T.Cole 正确我不确定,我可能会,response = HTTParty.get(data_url, options) 然后puts response ?然后看看我是否需要检查,迭代wtv。顺便说一句,你试过@response[:data] 吗?似乎在 Rails 5 中它默认符号化键
    【解决方案2】:

    尝试使用HTTParty::Responseparsed_response方法(这是您请求的响应)。 HTTParty.get(url, data).parsed_response

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-01
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多