Rails:如何显示用户的“最后一次看到"时间? [英] Rails: how to show user's "last seen at" time?

查看:17
本文介绍了Rails:如何显示用户的“最后一次看到"时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用存储 current_sign_in_atlast_sign_in_at 日期时间的设计.

I'm using devise which stores current_sign_in_at and last_sign_in_at datetimes.

但是假设一个用户在一个月前登录,但最后一次浏览页面是在 5 分钟前?

有什么方法可以显示(用户最后一次看到 5 分钟前").

Is there a way I can display that ("User last seen 5 minutes ago").

推荐答案

这个怎么样:

  1. 创建迁移以向用户添加新字段以存储用户上次出现的日期和时间:

  1. Create a migration to add a new field to users to store the date and time the user was last seen:

rails g migration add_last_seen_at_to_users last_seen_at:datetime

  • 向您的应用程序控制器添加一个 before action 回调:

  • Add a before action callback to your application controller:

    before_action :set_last_seen_at, if: proc { user_signed_in? }
    
    private
    def set_last_seen_at
      current_user.update_attribute(:last_seen_at, Time.current)
    end
    

  • 这样,对于当前用户执行的每个请求(即活动),他/她上次看到的 at 属性都会更新为当前时间.

    This way, on every request (i.e. activity) that the current user performs, his/her last seen at attribute is updated to the current time.

    但是请注意,如果您有很多用户登录,这可能会占用您应用的一些资源,因为这将在登录者请求的每个控制器操作之前执行.

    Please note, however, that this may take up some of your app's resources if you have many users who are logged in, because this will execute before every controller action requested by someone who is logged in.

    如果考虑性能,请考虑将以下节流机制添加到第 2 步(在此示例中,节流为 15 分钟):

    If performance is a concern, consider adding the following throttle mechanism to step 2 (in this example, throttling at 15 minutes):

    before_action :set_last_seen_at, if: proc { user_signed_in? && (session[:last_seen_at] == nil || session[:last_seen_at] < 15.minutes.ago) }
    
    private
    def set_last_seen_at
      current_user.update_attribute(:last_seen_at, Time.current)
      session[:last_seen_at] = Time.current
    end
    

    这篇关于Rails:如何显示用户的“最后一次看到"时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆