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

廉价感情. 提交于 2021-02-08 10:40:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!