Ruby on rails Rails:如何跟踪上次登录ip地址的用户?

Ruby on rails Rails:如何跟踪上次登录ip地址的用户?,ruby-on-rails,Ruby On Rails,我如何跟踪已登录用户的最后一个IP地址,而不是当前IP地址,因为我确信这可以通过 @ip = request.remote_ip 最好使用request.remote_ip,这很简单而且有效 class ApplicationController < ActionController::Base def remote_ip if request.remote_ip == '127.0.0.1' # Hard coded remote add

我如何跟踪已登录用户的最后一个IP地址,而不是当前IP地址,因为我确信这可以通过

@ip = request.remote_ip

最好使用
request.remote_ip
,这很简单而且有效

class ApplicationController < ActionController::Base
      def remote_ip
        if request.remote_ip == '127.0.0.1'
          # Hard coded remote address
          '123.45.67.89'
        else
          request.remote_ip
        end
      end
    end

    class MyController < ApplicationController
      def index
        @client_ip = remote_ip()
      end
    end

因为这考虑到了反向代理的大多数情况和您可能遇到的其他情况,其中
请求。env['REMOTE\u ADDR']
可能为零或本地代理的地址。

存储当前用户的IP地址是您访问最后一个用户的IP地址的方式。如果您在每次会话中都记录了登录用户的IP地址,那么最终将记录所有登录过的用户。要获取最后一个用户的IP地址,只需查询添加的最后一条记录

一个简单的解决方案是创建一个包含一列的表,并在运行时添加到该表中

下面是迁移文件的外观

class CreateUserIp < ActiveRecord::Migration[5.0]
  def change
    create_table :user_ip do |t|
      t.string :ip_address

      t.timestamps
    end
  end
end
现在,每次用户登录时,对于每个会话,您都可以将当前IP地址插入表中

UserIp.create(ip_address: request.remote_ip)
现在您可以像这样检索最新记录

last_users_ip = UserIp.order(created_at: :asc).reverse_order.limit(10).reverse.first

好了

使用gem进行身份验证(如果还不熟悉)。它提供了开箱即用的功能

将其保存在数据库中,以便下次进行比较!这看起来不像是一个解决方案?是的,但这不会获取登录用户在当前登录之前使用的ip地址session@RushRed我已经编辑了我的答案,你能核对一下吗
UserIp.create(ip_address: request.remote_ip)
last_users_ip = UserIp.order(created_at: :asc).reverse_order.limit(10).reverse.first