ruby-on-rails - Geocoder Gem - Ruby On Rails

标签 ruby-on-rails ruby-on-rails-3.1 google-geocoder

我刚刚将 Geocoder gem 包含到我的应用程序中。一切正常,但我想知道我是否可以进一步使用 gem。

我的应用程序有用户,他们可以添加文章。目前我可以使用他们的 IP 地址

 @article.ip_address = request.remote_ip

我一直在寻找可以帮助我将该 IP 地址转换为国家/地区名称的 gem,但我找不到任何东西。由于我使用的是地理编码器,我意识到在他们的网站上他们会自动检测我的 IP、城市和国家/地区。我想知道如何将其实现到我的 Controller 。
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/

最佳答案

您可以使用 geoip gem。

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

关于ruby-on-rails - Geocoder Gem - Ruby On Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7838581/

相关文章:

ruby-on-rails - 获取 ActiveRecord::Relation 的未定义方法

ruby-on-rails-3 - Rails 3.1 asset pipeline CSS 缓存正在开发中

ruby-on-rails - Ruby on Rails 服务器错误

ruby-on-rails - 如何修改 Active Admin 的 XML 和 XLSX 输出?

ruby-on-rails - Rollbar 忽略 ActiveRecord::RecordNotFound 异常

mysql - 如何在 ActiveRecord 中重新创建此查询

ruby-on-rails-3.1 - Rails 中的 after_destroy 回调顺序

javascript - Google Geocoding -- 解析可能返回不同的 address_components

google-maps - v3 Google Maps Geocoding API是否具有表示准确性的字段?

android - 无法使用 Geocoder 获取城市名称