繁体   English   中英

未定义的方法`[]'为nil:NilClass Rails 4

[英]undefined method `[]' for nil:NilClass Rails 4

我正在使用Weather Underground API处理天气应用程序。 在我的网络应用程序中,一切似乎都运行正常。 除了一件事。 什么时候我启动我的服务器并前往我的索引页面,在这种情况下,主页面。 我收到以下错误消息:未定义的方法[]' 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 index []' for nil:NilClass. Checking my logs, I see the following message: NoMethodError (undefined method '[]' for nil:NilClass):app/controllers/welcome_controller.rb:14

现在我的控制器看起来像这样:

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

现在,我已经找到了问题,我相信,对于params:state和:在我加载页面时没有填写城市。 如果我删除这部分代码:

  @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']

然后加载页面,如果我选择一个州和城市,一切都会正常工作,然后添加上面删除的代码 - 它会将其拉出来。 除了我无法启动我的服务器并直接进入我的索引页面,否则它将崩溃。 我还尝试将以下内容放入:

params[:state] = "MA"
params[:city] = "Boston"

这将加载页面就好了,除了我被困在波士顿! 最后,这是我的路线:

  #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'

任何帮助都会很棒! 我的所有代码都发布在github上,用户名是ravenusmc 再次,谢谢你的帮助。

一个或多个response字段可能为零。 这是一个非常常见的错误; 在尝试访问嵌套的哈希键或数组位置之前,应始终检查变量是否为空或空。 例如, @location = response['location']['city'] ,请使用以下内容:

@location = response['location'] ? response['location']['city'] : nil

@location = response... attributions的其余部分执行相同的@location = response...

如果您使用的是ruby 2.3.0,则可以使用dig方法:

@location = response.dig('location', 'city') 

它为您处理零值。 看到不同:

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.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM