地理编码宝石 - Ruby On Rails

4
我刚刚将Geocoder宝石包含在我的应用程序中。一切都很完美,但我想知道是否可以进一步使用这个宝石。
我的应用程序有用户,他们被允许添加文章。目前,我可以使用以下代码获取他们的IP地址:
 @article.ip_address = request.remote_ip

我一直在寻找一个可以帮助我将IP地址转换成国家名称的宝石,但是我找不到任何东西。由于我正在使用geocoder,并且我意识到他们的网站自动检测我的IP、城市和国家,我想知道如何将这个功能实现到我的控制器中。

def create
@article = Breeder.new(params[:breeder])
@article.user = current_user
@article.ip_address = request.remote_ip

respond_to do |format|
  if @article.save
    format.html { redirect_to @article, notice: 'Article was successfully created.' }
    format.json { render json: @article, status: :created, location: @article }
  else
    format.html { render action: "new" }
    format.json { render json: @article.errors, status: :unprocessable_entity }
  end
end

结束

这个想法是检测不来自英国的文章。

https://github.com/alexreisner/geocoder

http://www.rubygeocoder.com/

3个回答

4
你可以使用geoip宝石。
http://www.maxmind.com/app/geolitecountry下载GeoIP.dat.gz。解压缩文件。以下假设在#{RAILS_ROOT}/db目录下。
@geoip ||= GeoIP.new("#{RAILS_ROOT}/db/GeoIP.dat")    
remote_ip = request.remote_ip  
if remote_ip != "127.0.0.1" #todo: check for other local addresses or set default value
  location_location = @geoip.country(remote_ip)
  if location_location != nil     
    @model.country = location_location[2]
  end
end

0

是的,您可以使用Geocoder对IP地址进行地理编码。 Geocoder会向请求添加位置方法,因此您只需要:

sender_ip = request.remote_ip
sender_country = request.location.country
sender_city = request.location.city

对我来说可以。希望能帮到你。


0

谢谢这个,看起来很酷。哦,我该如何在上面的代码中实现它呢?再次感谢,一开始看起来真的很不错。 - Benjamin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接