DEV Community

Cover image for Ruby on Rails: How to see if User is online: TLDR
Yaroslav Shmarov
Yaroslav Shmarov

Posted on • Updated on • Originally published at blog.corsego.com

Ruby on Rails: How to see if User is online: TLDR

Here's the easiest way:

  • Whenever the current_user does any action, his updated_at will be set as Time.now.

application_controller.rb

after_action :update_user_online, if: :user_signed_in?

private

def update_user_online
  current_user.try :touch
end
Enter fullscreen mode Exit fullscreen mode
  • And we will just say that the user is online if he was updated_at during the last 2.minutes

user.rb

def online?
  updated_at > 2.minutes.ago
end
Enter fullscreen mode Exit fullscreen mode
  • Now we can get true or false if we make a call like @user.online?

users/show.html.erb

<%= @user.online? %>
Enter fullscreen mode Exit fullscreen mode

That's it!🤠

Liked this article? Please follow me! It will really motivate me to post more fun stuff!

Top comments (0)