DEV Community

loading...
Cover image for Ruby on Rails: How to see if User is online: TLDR

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

yaro_the_slav profile image Yaroslav Shmarov Originally published at blog.corsego.com Updated on ・1 min read

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!

Discussion

pic
Editor guide