Search code examples
ruby-on-railsdeviseruby-on-rails-6

"User last online" at <time> using devise?


Is there any easy/native way to display when a user was last online on their profile page using a standard rails app using devise for authentication?

The closest I can get is

<%= @user.current_sign_in_at.to_s %>

This shows the last time a sign in occurred (which could differ significantly from the last time the user checked the site - i.e the last time they were 'online' so to speak). For example, I'd like to show a little green light if the user was using the site anytime in the last 90 seconds, but that won't be accurate if using the time of their last sign in.


Solution

  • Add a column in a users table last_seen_at & update it every time using touch.

    class ApplicationController
      before_action :record_last_seen_at
    
      private
    
      def record_last_seen_at
        if current_user
          current_user.touch :last_seen_at
        end
      end
    end