【发布时间】:2017-07-11 04:40:34
【问题描述】:
尝试在 Ruby on Rails 中使用 HTTParty 解析 JSON 时,我不断收到此错误:"undefined method `[]' for nil:NilClass"。
我希望能够使用 API,但无法让任何东西工作。
URL 工作正常,返回 JSON 元素没有问题;由于某种奇怪的原因,我无法访问它们并展示它们。
我正在使用 Rails 5 和 Ruby 2.4。所有 API 密钥都是隐藏的,但可以正确输入到我的 Rails 应用程序中。
这是我的 lib 文件:
require 'httparty'
class Wunderground
include HTTParty
format :json
base_uri 'api.wunderground.com'
attr_accessor :temp, :location, :icon, :desc, :url, :feel_like
def initialize(response)
@temp = response['current_observation']['temp_f']
@location = response['current_observation']['display_location']['full']
@icon = response['current_observation']['icon_url']
@desc = response['current_observation']['weather']
@url = response['current_observation']['forecast_url']
@feel_like = response['current_observation']['feelslike_f']
end
def self.get_weather(state, city)
response = get("/api/#{ENV["wunderground_key"]}/conditions/q/#{state}/#{city}.json")
if response.success?
new(response)
else
raise response.response
end
end
end
我已将 我的 api 密钥 输入到我的 application.yml 文件中,如下所示:
wunderground_key: "YOUR_API_KEY"
我的控制器:
class HomeController < ApplicationController
require 'Wunderground'
def wunderground
@weather = Wunderground.get_weather(params[:state], params[:city])
end
def index
end
end
我的路线:
root 'home#index'
get 'wunderground', to: 'home#wunderground'
我的看法:
<div>
<%= form_tag wunderground_path, method: "get", class: "form-inline" do %>
<%= text_field_tag :city, nil, class: "form-control", placeholder: "City Name" %>
<%= select_tag :state, options_for_select(@states), :prompt => "Please select", class: "form-control" %>
<%= submit_tag "Check Weather", name: nil, class: "btn btn-primary" %>
<% end %>
</div>
<div>
<% if @weather.present? %>
<h3><%= @weather.location %></h3>
<p>The temperature is:
<%= @weather.temp %></p>
<p>Feels like:
<%= @weather.feel_like %></p>
<p>
<%= @weather.desc %>
<%= image_tag @weather.icon %>
</p>
<p>
<%=link_to "Full Forecast", @weather.url, target: "_blank" %>
</p>
</div>
<% end %>
编辑:
这是我在开发日志中看到的错误:
NoMethodError (undefined method `[]' for nil:NilClass):
lib/Wunderground.rb:12:in `initialize'
lib/Wunderground.rb:23:in `new'
lib/Wunderground.rb:23:in `get_weather'
app/controllers/home_controller.rb:6:in `wunderground'
【问题讨论】:
-
在
get_weather方法中发布完整的错误日志和response变量中的值。 -
已编辑以反映开发日志中显示的完整错误。 “响应”是 Wunderground API 在访问 API 时返回的内容。
-
我认为
response或response['current_observation']是nil。这就是您收到此错误的原因。如果你发布response变量的值,很容易找到原因。
标签: ruby-on-rails json ruby-on-rails-5 httparty