我正尝试创建一个根据位置当前的天气情况返回gif网址的应用。我正在使用开放式天气api,并将网址存储在模块中的哈希中,并创建了一种根据api调用返回的天气代码选择gif网址的方法。例如,代码321对应于“小雨”,然后应返回描述小雨的gif。
当我运行代码时,出现参数错误Nil location provided. Can't build URI
,我不确定是否以正确的方式访问了helper方法。 API调用工作正常,我可以返回@weather_code
到我的视图,没问题。知道是什么原因造成的吗?这是我的代码:
forecasts_helper.rb
module ForecastsHelper
GIFS = {
thunder:
{codes: [200, 201, 202, 210, 211, 212, 221, 230, 231, 232],
urls: %w(
https://media.giphy.com/media/26uf5HjasTtxtNCqQ/giphy.gif
https://media.giphy.com/media/vS09bj1KrXwje/giphy.gif
https://media.giphy.com/media/2pUAUd0cFntny/giphy.gif
)},
light_rain:
{codes: [300, 301, 302, 310, 311, 312, 313, 314, 321, 500, 501, 520, 521],
urls: %w(
https://media.giphy.com/media/xT9GEz2CeU9uaI2KZi/giphy.gif
https://media.giphy.com/media/k28n1OPefBEeQ/giphy.gif
https://media.giphy.com/media/H1eu9Vw957Rfi/giphy.gif
)},
heavy_rain:
{codes: [502, 503, 504, 522, 531, 511],
urls: %w(
https://media.giphy.com/media/1Yfxps0AHRYBR2tK2G/giphy.gif
https://media.giphy.com/media/hk6czgfmwVJS0/giphy.gif
https://media.giphy.com/media/26BGD4XaoPO3zTz9K/giphy.gif
)}
}
def find_gif_url
GIFS.each do |key, value|
if value[:codes].include? @weather_code
value[:urls].sample
end
end
end
end
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
@temperature = @forecast.dig('main', 'temp').to_i - 273
@weather_code = @forecast.dig('weather', 0, 'id').to_i
end
end
current_weather.html.erb
<%= form_tag(current_weather_forecasts_path, method: :get) do %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %><br>
<%= image_tag(find_gif_url, class: "gif") %>
答案 0 :(得分:3)
您正在遍历所有GIFS
,但是在有匹配的代码时不返回。更改
def find_gif_url
GIFS.each do |key, value|
if value[:codes].include? @weather_code
value[:urls].sample
end
end
end
到
def find_gif_url
GIFS.each do |key, value|
if value[:codes].include? @weather_code
return value[:urls].sample
end
end
end