HTTParty未定义的方法' +'为零:NilClass

时间:2016-03-30 22:29:45

标签: ruby-on-rails httparty

使用HTTParty gem连接到weather API我有以下方法:

def weather_search
  @city_name = params[:city_name]
  url = URI.encode("api.openweathermap.org/data/2.5/weather?q=#{@city_name}&APPID=#{API_TOKEN}")
  @search_result = HTTParty.get(url)
end

安装了宝石。

使用邮递员,我可以使用以下网址

轻松访问API
api.openweathermap.org/data/2.5/weather?q=banfield&APPID=xxxxxxxxxxxxxxx

但是在我的rails 4 app中,同一个url会抛出错误

我宣布

的行上的

undefined method '+' for nil:NilClass

@search_result = HTTParty.get(url)

我发现thisthis other发布了这个主题,但两者都无济于事。

堆栈追踪:

Started POST "/search_city_weather" for 127.0.0.1 at 2016-03-30 23:50:13 +0100
Processing by WeatherChecksController#weather_search as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "city_name"=>"banfield", "commit"=>"Search"}
api.openweathermap.org/data/2.5/weather?q=banfield&APPID=xxxxxxxxxxxxxxxxxx
Completed 500 Internal Server Error in 11ms
NoMethodError (undefined method `+' for nil:NilClass):
  app/controllers/weather_checks_controller.rb:24:in `weather_search'
  Rendered /home/xxxx/.rvm/gems/ruby-2.2.2/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_source.erb (1.3ms)
  Rendered /home/xxxx/.rvm/gems/ruby-2.2.2/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.1ms)
  Rendered /home/xxxx/.rvm/gems/ruby-2.2.2/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.3ms)
  Rendered /home/xxxx/.rvm/gems/ruby-2.2.2/gems/actionpack-4.1.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (22.6ms)

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

正如@tadman所写,您应该为httparty提供有效的URI, 这样:

顺便提到比0.14.0更新的版本, 在这些情况下,Httparty将返回此错误: URI::InvalidURIError: bad URI(is not URI?):

比这更清楚

undefined method '+' for nil:NilClass