4

我正在尝试通过他们的 IP 地址本地化我的用户。正如文档所说,一个名为的类方法geocode_ip_address已混入ActionController::Base. 但一定有什么我错过了。我是否必须定义这样的过滤器before_filter :geocode_ip_address才能使用它?(我想知道完成的每个请求的位置)。

该文档还谈到“首次查找将导致 GeoLoc 类存储在会话中:geo_location”,但我当然在会话哈希中没有该密钥。

我究竟做错了什么?

谢谢。

4

1 回答 1

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将为零。如果您在开发中运行,您将尝试对 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
于 2011-05-10T16:16:07.653 回答