Geocoder gem 在 heroku 服务器中创建问题

Geocoder gem creating issue in heroku server

您好,我在 gem 文件

中包含了以下 gem

gem 'geocoder'

并在我的视图文件中编写了以下代码

- @location = Geocoder.search(request.remote_ip).first.country
%div{"class" => "currentCountry", "value" => "#{@location}"}
- if session[:browser] == 'mobile'
  testmobile
- else
  testdesktop

在 heroku 服务器中它给我错误,而在我的本地服务器中它工作正常。

ActionView::Template::Error (undefined method `country' for nil:NilClass):
2016-02-16T07:47:14.447459+00:00 app[web.1]: 
2016-02-16T07:47:14.447455+00:00 app[web.1]:     3: - if session[:browser] == 'mobile'
2016-02-16T07:47:14.447456+00:00 app[web.1]:     4:   = render 'mobile'
2016-02-16T07:47:14.447457+00:00 app[web.1]:   app/views/spree/checkout/edit.html.haml:1:in `_b6865a451d7a5a040f6c1f6376727300'
2016-02-16T07:47:14.447458+00:00 app[web.1]: 
2016-02-16T07:47:14.447454+00:00 app[web.1]:     1: - @location = Geocoder.search(request.remote_ip).first.country
2016-02-16T07:47:14.447454+00:00 app[web.1]:     2: %div{"class" => "currentCountry", "value" => "#{@location}"}

请指导为什么我在 heroku 服务器中遇到此错误。

geocoder_result = Geocoder.search(request.remote_ip)

@location = geocoder_result.empty? ? "" : geocoder_result.first.country

我之前经历过这个,这是因为请求超时并且响应为零。原因是:-

  • :ip_lookup(默认-freegeoip)
  • :超时(默认 - 3 秒)

Freegeoip 作为一项免费服务通常会超载,有时可能会延迟响应,并且由于默认超时设置为 3 秒,请求会超时并且 returns nil 作为导致此问题的响应(相同已讨论here)。

解决方案:-

  • 切换到一些付费的 ip 查询服务(其他选项 here)以获得更好更快的服务。(推荐)
  • 继续使用 freegeoip,但将超时增加到 7-8 秒,这样请求就不会很快超时(不推荐用于生产应用程序)

选项 ip_lookup 和超时都可以在初始化程序中配置(查看 here 了解更多信息,谢谢。