Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Who's Online" using Devise in Rails

Using Devise on Rails, is there some way to list all the users who currently have active sessions i.e. the users that are currently logged in?

Ps. I'm looking for a robust solution, not something simplistic like the ones in this question

like image 923
Zabba Avatar asked Mar 31 '11 17:03

Zabba


3 Answers

Simply add after_filter in ApplicationController

after_filter :user_activity

private

def user_activity
  current_user.try :touch
end

Then in user model add online? method

def online?
  updated_at > 10.minutes.ago
end

Also u can create scope

scope :online, lambda{ where("updated_at > ?", 10.minutes.ago) }
like image 59
Yuri Barbashov Avatar answered Nov 20 '22 23:11

Yuri Barbashov


https://github.com/ctide/devise_lastseenable

You can use this gem that I wrote to store the 'last_seen' timestamp of a user. From there, it's pretty trivial to display the users who were last_seen in the last 5 or 10 minutes.

like image 24
ctide Avatar answered Nov 20 '22 22:11

ctide


If you're bothered by making a trip to database on every. single. http. request. only to have some small window where you can sort of assume that a user is online; I have an alternate solution.

Using websockets and redis it's possible to reliably get a user's online status up to the millisecond without making a billion costly writes to disk. Unfortunately, it requires a good bit more work and has two additional dependencies, but if anybody's interested I did a pretty detailed write here:

How do I tell if a user is online?

like image 20
Ryan Epp Avatar answered Nov 20 '22 23:11

Ryan Epp