【发布时间】:2019-06-06 17:49:20
【问题描述】:
我有一个简单的应用程序,它调用 API 并返回天气数据。用户可以搜索城市并返回当前温度。但是我有一个问题,当搜索字段为空或无法识别的城市时,我收到错误 undefined method[]' for nil:NilClass`。这是我的代码:
forecasts_controller.rb
class ForecastsController < ApplicationController
def current_weather
@token = Rails.application.credentials.openweather_key
@city = params[:q]
if @city == nil
@forecast = ""
else
@forecast = OpenWeatherApi.new(@city, @token).my_location_forecast
end
end
end
服务/open_weather_api.rb
class OpenWeatherApi
include HTTParty
base_uri "http://api.openweathermap.org"
def initialize(city, appid)
@options = { query: { q: city, APPID: appid } }
end
def my_location_forecast
self.class.get("/data/2.5/weather", @options)
end
end
current_weather.html.erb
<%= form_tag(current_weather_forecasts_path, method: :get) do %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %><br>
<p>Current temperature: <%= @forecast['main']['temp'].to_i - 273 %>°C</p>
显然代码['main']['temp'].to_i - 273 不能在nil 上调用,但是当表单中没有传递任何内容或API 无法识别城市时,如何防止@forecast 成为nil?
【问题讨论】:
-
为什么不在
<% if @forecast.present? %> ... <% end %>中换行呢?此外,默认@forecast为""不是惯用的,最好将其定义为nil(或者根本不定义它,因为无论如何默认情况下实例变量都是 nil)。
标签: ruby-on-rails ruby httparty openweathermap