DEV Community

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

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

4 4

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!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs