简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM