Rails:如何在Rails应用程序中查找登录用户? [英] Rails: How to find out logged users in my rails application?

查看:58
本文介绍了Rails:如何在Rails应用程序中查找登录用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户登录时,我将用户ID从数据库保存到 session [:user_id] 中.我应该怎么做才能找到已登录的用户数?

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?

我将 ActionDispatch :: Session :: CacheStore 用于会话存储.

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

请指导我实现目标的正确方法.

Please guide me the correct way to achieve my objective.

推荐答案

可能最好的解决方案是切换到使用Active Record会话存储.这很容易-您只需要添加(并运行)迁移即可创建会话表.只需运行:

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

然后将会话存储配置添加到: config/initializers/session_store.rb 如下:

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

YourApplication::Application.config.session_store :active_record_store

完成此操作并重新启动服务器后,Rails现在将把会话存储在数据库中.

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

尽管仅对最近更新的那些进行计数(例如最近5分钟)会更准确:

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.

这篇关于Rails:如何在Rails应用程序中查找登录用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆