问题
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.
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/24431590/rails-how-to-find-out-logged-users-in-my-rails-application