我将如何跟踪用户中签名的最后一个IP地址,而不是当前签名,因为我敢肯定可以通过
来实现。@ip = request.remote_ip
存储当前用户的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
确保从终端运行迁移
rails db:migrate
现在,每次用户登录时,对于每个会话,您都可以将当前的IP地址插入表中。
UserIp.create(ip_address: request.remote_ip)
现在您可以检索最新记录,
last_users_ip = UserIp.order(created_at: :asc).reverse_order.limit(10).reverse.first
你去!
使用设计宝石进行身份验证(如果尚不熟悉)。它提供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
当您在本地访问网站时,您将来自本地IP地址,即127.0.0.1。
您正在做的是访问者IP地址的正确方法,而您看到的结果如预期。
您想使用
@ip = request.remote_ip
因为这考虑了大多数反向代理和其他情况的情况,您可能会遇到request.env['REMOTE_ADDR']
可能为nil或本地代理的地址。