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

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

问题描述

我正在使用devise,它存储 current_sign_in_at last_sign_in_at datetimes。

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. 创建一个迁移,为用户添加一个新的字段来存储用户上次看到的日期和时间: / p>

  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.now)
    end
    


  • 这样,在当前用户执行的每个请求(即活动)上,他/她最后一次在属性更新到当前时间。

    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.now)
      session[:last_seen_at] = Time.now
    end
    

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

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