Geokit助手的用法

时间:2011-04-21 13:03:59

标签: ruby-on-rails-3 geokit

我正在尝试通过他们的IP地址本地化我的用户。正如文档所说,名为geocode_ip_address的类方法已混合到ActionController::Base中。但是必须有一些我想念的东西。我是否必须定义像此before_filter :geocode_ip_address这样的过滤器才能使用它? (我想知道每个请求的位置)。

该文档还讨论了“首次查找将导致GeoLoc类作为:geo_location存储在会话中”但我当然没有在会话哈希中使用该密钥。

我做错了什么?

感谢。

1 个答案:

答案 0 :(得分:5)

您不需要将 before_filter 添加到geocode_ip_address,而只需将其放在您的控制器中:

class YourController < ApplicationController
  geocode_ip_address

  def action
    if geo = session[:geo_location]
      # geo here is a Geokit::GeoLoc object
    end
  end
end

请注意,如果地理编码失败, geo 将为nil。如果您正在开发中运行,那么您将尝试对127.0.0.1进行地理编码,因此您需要在请求对象中设置remote_ip。我这样做是通过将其添加到 config / environments / development.rb 的底部:

class ActionDispatch::Request
  def remote_ip
    "x.x.x.x" # fill in your IP address here
  end
end