2011-10-20 187 views
4

我剛把Geocoder gem包含到了我的應用程序中。一切都很完美,但我想知道如果我可以進一步使用寶石。地理編碼器寶石 - Ruby On Rails

我的應用程序有用戶,他們被允許添加文章。目前,我可以將其IP地址使用

@article.ip_address = request.remote_ip 

我已經找了一個寶石,它可以幫助我轉換成該IP地址的國家名字,但我無法找到任何東西。由於我使用地理編碼器,我意識到在他們的網站上他們會自動檢測我的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/

回答

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

是的,您可以使用地理編碼器對地址進行地理編碼。地理編碼器會添加一個定位方法到請求,所以你只需要:

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

這對我很有用。希望能幫助到你。