4

我刚刚将 Geocoder gem 包含在我的应用程序中。一切都很完美,但我想知道我是否可以进一步使用 gem。

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

 @article.ip_address = request.remote_ip

我一直在寻找可以帮助我将该 IP 地址转换为国家名称的 gem,但我找不到任何东西。由于我使用的是地理编码器,并且我意识到在他们的网站上他们会自动检测我的 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

3 回答 3

4

您可以使用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
于 2011-10-20T18:18:25.033 回答
0

也许 GeoIP 是您的替代方案:

https://github.com/cjheath/geoip

它真的很简单。我对地理编码器没有那么自信,但如果你定义飞想使用它,你可能会观看处理它的 railscast。

http://railscasts.com/episodes/273-geocoder

Rails 编码女性,该死的热!^^

于 2011-10-20T15:54:06.837 回答
0

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

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

这对我行得通。希望能帮助到你。

于 2014-09-01T20:39:37.797 回答