2013-11-26 77 views
-1

我使用Ruby on Rails 4.0.1。如何了解访问者位置导轨

我发展链接短服务,所以我需要找到我的用户的位置。例如英国,土耳其,比利时。

我如何在Rails中做到这一点?

回答

1

使用GeoCoder Gem。它可以让你找到用户的位置。

Geocoder是一个完整的Ruby地理编码解决方案。通过Rails,它添加​​了地理编码(通过街道或IP地址),反向地理编码(查找基于给定坐标的街道地址)和距离查询。就像在对象上调用地理编码一样简单,然后使用Venue.near(“Billings,MT”)等作用域。

GeoCoder

0

我使用http://www.ip2nation.com的数据从IP地址中找到访问者的国家。从这个网站你可以下载一个文件来创建和填充表格ip2nation。接下来我创建了这种类型的模型:

require 'ipaddr'  

# 2 columns: ip and country 
class Ip2nation < ActiveRecord::Base 
    self.table_name = 'ip2nation' 
    self.primary_key = :ip 

    #------------- Finder 

    # Get the country code for the given ip string 
    def self.find_country(ip) 

    # Convert the ip to a number 
    ip_number = IPAddr.new(ip).to_i 

    # Find the country in the database 
    where('ip < ?', ip_number).order(:ip).pluck(:country).last  
    end 
end 

而且使用这样的:

country = Ip2nation.find_country(request.remote_ip)