我正在尝试通过他们的 IP 地址本地化我的用户。正如文档所说,一个名为 geocode_ip_address
的类方法已混入ActionController::Base
.但一定有我遗漏的东西。我是否必须定义这样的过滤器 before_filter :geocode_ip_address
使用它? (我想知道每个请求完成的位置)。
该文档还谈到“首次查找将导致 GeoLoc 类作为 :geo_location
存储在 session 中”,但我当然在 session 哈希中没有该键。
我究竟做错了什么?
谢谢。
最佳答案
您不需要预先添加 before_filter 到 geocode_ip_address,而只是把它放在你的 Controller 中:
class YourController < ApplicationController
geocode_ip_address
def action
if geo = session[:geo_location]
# geo here is a Geokit::GeoLoc object
end
end
end
请注意,如果地理编码失败 地理 将为零。如果您正在开发中运行,您将尝试对 127.0.0.1 进行地理编码,因此您需要在请求对象中设置您的 remote_ip。我这样做是通过将它添加到 的底部来实现的。配置/环境/development.rb :
class ActionDispatch::Request
def remote_ip
"x.x.x.x" # fill in your IP address here
end
end
关于ruby-on-rails-3 - Geokit 助手的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5744490/