[英]undefined method `[]' for nil:NilClass Rails 4
I am working on a weather app using the Weather Underground API. 我正在使用Weather Underground API处理天气应用程序。 Everything almost appears to be working fine in my web app.
在我的网络应用程序中,一切似乎都运行正常。 Except for one thing.
除了一件事。 When ever I start up my server and head to my index page, in this case, the main page.
什么时候我启动我的服务器并前往我的索引页面,在这种情况下,主页面。 I get the following error message: undefined method
[]' for nil:NilClass. Checking my logs, I see the following message: NoMethodError (undefined method '[]' for nil:NilClass):app/controllers/welcome_controller.rb:14
我收到以下错误消息:未定义的方法
[]' for nil:NilClass. Checking my logs, I see the following message: NoMethodError (undefined method '[]' for nil:NilClass):app/controllers/welcome_controller.rb:14
[]' for nil:NilClass. Checking my logs, I see the following message: NoMethodError (undefined method '[]' for nil:NilClass):app/controllers/welcome_controller.rb:14
in index
. []' for nil:NilClass. Checking my logs, I see the following message: NoMethodError (undefined method '[]' for nil:NilClass):app/controllers/welcome_controller.rb:14
index
[]' for nil:NilClass. Checking my logs, I see the following message: NoMethodError (undefined method '[]' for nil:NilClass):app/controllers/welcome_controller.rb:14
。
now my controller looks like this: 现在我的控制器看起来像这样:
class WelcomeController < ApplicationController
def index
#states will need to be defined and then @states.sort will sort all of them on the form.
@states = %w(HI AK CA OR WA ID UT NV AZ NM CO WY MT ND SD NE KS OK TX LA AR
MO IA MN WI IL IN MI OH KY TN MS AL GA FL SC NC VA WV DE MD PA NY NJ CT RI
MA VT NH ME DC PR)
@states.sort!
#Here is the call to the API
response = HTTParty.get("http://api.wunderground.com/api/#
{ENV['wunderground_api_key']}/geolookup/conditions/q/#{params[:state]}/#
{params[:city]}.json")
@location = response['location']['city']
@temp_f = response['current_observation']['temp_f']
@temp_c = response['current_observation']['temp_c']
@weather_icon = response['current_observation']['icon_url']
@weather_words = response['current_observation']['weather']
@forecast_link = response['current_observation']['forecast_url']
@real_feel = response['current_observation']['feelslike_f']
#This part of the code will change the background depending on what
@weather_words is.
#Head over to the views/layouts/application.html.erb file to see more.
if @weather_words == "Partly Cloudy" || @weather_words == "Mostly Cloudy"
@body_class = "partly-cloudy"
elsif @weather_words == "Cloudy" || @weather_words == "Scattered Clouds" || @weather_words == "Overcast"
@body_class = "partly-cloudy"
elsif @weather_words == "Clear"
@body_class = "sunny"
elsif @weather_words == "snow"
@body_class = "snow"
elsif @weather_words == "Rain"
@body_class = "rain"
elsif @weather_words == "Fog"
@body_class = "fog"
elsif @weather_words == "Thunderstorms and Rain" || @weather_words == "Thunderstorms"
@body_class = "thunder"
end
end
Now, I have tracked down the problem, I believe, to the params :state and :city not being filled in when I load the page. 现在,我已经找到了问题,我相信,对于params:state和:在我加载页面时没有填写城市。 If I delete this part of the code:
如果我删除这部分代码:
@location = response['location']['city']
@temp_f = response['current_observation']['temp_f']
@temp_c = response['current_observation']['temp_c']
@weather_icon = response['current_observation']['icon_url']
@weather_words = response['current_observation']['weather']
@forecast_link = response['current_observation']['forecast_url']
@real_feel = response['current_observation']['feelslike_f']
Then load the page, everything will work fine if I select a state and city, then add the above deleted code-it will pull it up. 然后加载页面,如果我选择一个州和城市,一切都会正常工作,然后添加上面删除的代码 - 它会将其拉出来。 Except I cannot start my server and go directly to my index page or else it will crash.
除了我无法启动我的服务器并直接进入我的索引页面,否则它将崩溃。 I also tried placing the following in:
我还尝试将以下内容放入:
params[:state] = "MA"
params[:city] = "Boston"
and that will load the page just fine except I am stuck on Boston! 这将加载页面就好了,除了我被困在波士顿! Finally, Here are my routes:
最后,这是我的路线:
#The index page gets two routes:
#The get route for when we initially come to the page
get 'index' => 'welcome#index'
#And then a post route for when we come back to the index page after
# submitting the form
post 'index' => 'welcome#index'
Any help will be great! 任何帮助都会很棒! I also have all of my code posted at github, username is
ravenusmc
. 我的所有代码都发布在github上,用户名是
ravenusmc
。 Again, thank you for the help. 再次,谢谢你的帮助。
One or more fields of response
are probably nil. 一个或多个
response
字段可能为零。 This is a very common mistake; 这是一个非常常见的错误; you should always check if the variable is nil or empty before trying to access nested hash keys or array positions.
在尝试访问嵌套的哈希键或数组位置之前,应始终检查变量是否为空或空。 eg, insted of
@location = response['location']['city']
, use something like: 例如,
@location = response['location']['city']
,请使用以下内容:
@location = response['location'] ? response['location']['city'] : nil
Do the same for the rest of the @location = response...
attributions. 对
@location = response...
attributions的其余部分执行相同的@location = response...
。
If you're using ruby 2.3.0, you can use the dig
method: 如果您使用的是ruby 2.3.0,则可以使用
dig
方法:
@location = response.dig('location', 'city')
Which handles nil values for you. 它为您处理零值。 See the difference:
看到不同:
2.3.0 :004 > response = {}
# => {}
2.3.0 :005 > response.dig('location', 'city')
# => nil
2.3.0 :006 > response['location']['city']
NoMethodError: undefined method `[]' for nil:NilClass
from (irb):6
from /home/lbrito/.rvm/rubies/ruby-2.3.0/bin/irb:11:in `<main>'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.