You need to enable JavaScript to run this app. 使用Devise认证的Rails应用如何在用户资料页展示用户最后在线时间
优惠活动
大模型
产品
解决方案
定价
更多

使用Devise认证的Rails应用如何在用户资料页展示用户最后在线时间

实现用户最后在线时间的轻量化原生方案

你当前用到的current_sign_in_at、last_sign_in_at都是Devise仅在用户执行登录/登出动作时才会更新的字段,后续用户在站点内的浏览、交互操作完全不会触发这些字段更新,和真实的最后访问时间自然存在很大偏差,根本不适合用来判断实时在线状态。

完全不用引入复杂第三方依赖,用Rails和Devise的原生能力就能快速实现你要的90秒在线判断逻辑:

1. 给用户表新增存储最后访问时间的字段

先通过生成迁移添加可空的datetime类型字段:

rails generate migration AddLastSeenAtToUsers last_seen_at:datetime
rails db:migrate

这个字段会专门用来记录用户每一次和站点交互的时间点,和Devise自带的登录时间字段完全独立,不会干扰原有认证逻辑。

2. 在全局控制器钩子中更新访问时间

把更新逻辑放在ApplicationController里,只对已登录用户触发,同时加必要的节流逻辑,避免每一次页面请求都写一次数据库造成性能浪费:

class ApplicationController < ActionController::Base
  before_action :refresh_last_seen_time, if: :user_signed_in?

  private

  def refresh_last_seen_time
    # 超过15秒才更新一次数据库,足够支撑90秒的在线判断精度,同时大幅降低写入压力
    current_user.touch(:last_seen_at, time: Time.current) if current_user.last_seen_at < 15.seconds.ago
  end
end

3. 封装在线状态判断逻辑

直接在User模型里加一个实例方法,视图层就可以直接调用判断:

class User < ApplicationRecord
  def online?
    last_seen_at.present? && last_seen_at > 90.seconds.ago
  end
end

对应的视图渲染代码就很简单:

<% if @user.online? %>
  <span class="inline-block w-2 h-2 rounded-full bg-green-500"></span> 在线
<% else %>
  <span class="inline-block w-2 h-2 rounded-full bg-gray-300"></span>
  <% if @user.last_seen_at %>
    最后在线:<%= @user.last_seen_at.strftime("%m月%d日 %H:%M") %>
  <% else %>
    从未上线
  <% end %>
<% end %>

实际落地的优化细节

  • 对纯API请求、静态资源请求可以直接跳过更新逻辑,进一步减少无意义的数据库写入
  • 如果站点访问量较高,可以把时间更新先写入Redis缓冲,每分钟批量同步到数据库,避免单表写入压力过大
  • 整个实现逻辑不到20行代码,没有额外gem依赖,和Devise的认证流程完全兼容,不存在逻辑冲突

注:目前能搜到的同类功能插件,核心逻辑和上面的实现完全一致,只是把这套逻辑做了封装,自己写反而更灵活,方便随时调整节流间隔、在线判断的时间窗口。

内容的提问来源于stack exchange,提问作者stevec

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.26 16:45:04