我应该如何使用 Geocoder 中的 request.ip 访问器来获取用户当前的 ip?

How should I use the request.ip accessor from Geocoder to get user current ip?

我很难找到如何在我的 Rails 应用程序上使用 Geocoder gem 在创建新的 User 实例时获取和保存 IP 地址。

Geocoder 有一些有用的功能,例如获取当前 ip 位置的访问器和一些其他位置信息,但我对 Rails 还是个新手,如果文档有更多指导就更好了: -)

只要我使用 ActiveRecord,我就会从创建以下迁移开始:

rails generate migration AddIpAddressToUser ip_address:float       

然后我将其添加到 app/models/user.rb

geocoded_by :ip_address,
  :latitude => :lat, :longitude => :lon
after_validation :geocode

我 运行 迁移以在 schema.rb 上添加这些修改:

rails db:migrate            

现在有用户模型的当前架构:User.rb 在其架构上有纬度、经度和 ip_address。

那我怎么用下面的方法呢?

  1. request.ip
  2. request.location

根据 Rails documentation:

For every request, the router determines the value of the controller and action keys. These determine which controller and action are called. The remaining request parameters, the session (if one is available), and the full request with all the HTTP headers are made available to the action through accessor methods. Then the action is performed.

The full request object is available via the request accessor

因此,当用户访问您的网站或 API 调用发送到您的应用程序时,在控制器中,您可以访问 request 对象。如何使用这些数据取决于您。

例如,在你的控制器的 index 方法中你可以有类似的东西:

def index
  geocoder_result = request.location
  #do something based on the geocoder_result
end

在 Rails 中,模型无法识别请求。因此,要将 IP 分配给您需要从控制器执行的用户:

class UserController < ApplicationController
  def create
    @user = User.new(user_params) do |u|
      u.ip_address = request.location
    end
    # ...
  end
end

如果您使用的是 Devise,您可以重写 build_resource 方法:

# Adds request IP to the user to determine location.
class MyRegistrationsController < Devise::RegistrationsController
  def build_resource(hash={})
    super(hash.merge(ip_address: request.location))
  end
end

# routes.rb
devise_for :users, controllers: { registrations: "my_registrations"}

您可以使用此

基于地理编码器获取国家/地区位置

国家= ISO3166::Country.new(Geocoder.search(ip).first.country_code)

我们正在使用它来获取有关该 IP 位置的国家和默认货币的信息。