user1538633
user1538633

Reputation: 139

Rails: How to find out logged users in my rails application?

I save user ids to session[:user_id] from database when user logs in . What should I do to find out number of logged in users?

I use ActionDispatch::Session::CacheStore for session storage.

Please guide me the correct way to achieve my objective.

Upvotes: 0

Views: 2319

Answers (2)

stuartbates
stuartbates

Reputation: 229

Probably the best solution would be to switch to using the Active Record Session store. It's easy to do - you just need to add (and run) the migration to create the sessions table. Just run:

rake db:sessions:create

Then add the session store config to: config/initializers/session_store.rb like so:

YourApplication::Application.config.session_store :active_record_store

Once you've done that and restarted your server Rails will now be storing your sessions in the database.

This way you'll be able to get the current number of logged in users using something like:

ActiveRecord::SessionStore::Session.count

Although it would be more accurate to only count those updated recently - say the last 5 minutes:

ActiveRecord::SessionStore::Session.where("updated_at > ?", 5.minutes.ago).count

Depending on how often you need to query this value you might want to consider caching the value or incrementing/decrementing a cached value in an after create or after destroy callback but that seems like overkill.

Upvotes: 3

user401093
user401093

Reputation: 186

When a session is created or destroyed, you could try implementing a session variable that increments or decrements and use some helpers to increment/decrement the counter.

def sessions_increment
  if session[:count].nil?
    session[:count] = 0
  end
  session[:count] += 1
end
def sessions_decrement
  if session[:count].nil?
    session[:count] = 0
  end
  session[:count] -= 1
end

Upvotes: 0

Related Questions