简体   繁体   English

Rails 3 +设计:user_signed_in?对于数据库中的其他用户?

[英]Rails 3 + Devise: user_signed_in? for a different user in the database?

I'm building an app where I want to add an online status for a given user. 我正在构建一个应用程序,我想为给定用户添加在线状态。

I know that Devise has a method user_signed_in? 我知道Devise有一个方法user_signed_in? built in to check if the user who is using the app is signed in or not. 内置以检查使用该应用程序的用户是否已登录。 But when I try to use it for a different user like this: 但是当我尝试将它用于不同的用户时:

user_signed_in?(user)

user.user_signed_in?

I obviously get an undefined method error. 我显然得到一个未定义的方法错误。

Does Devise have a method for this or do I have to write my own? Devise有这个方法还是我必须自己编写? One approach was to store the online status of a given user in the user model. 一种方法是将给定用户的在线状态存储在用户模型中。 What's the best solution to this? 什么是最好的解决方案?

I have used Devise on my applications and experienced some of the same problems as you when I first began working with it. 我在我的应用程序上使用了Devise,并在我第一次使用它时遇到了一些与你相同的问题。 You are merely using the helper methods incorrectly. 您只是错误地使用辅助方法。 If you'd like to check if the current user has a session and is signed in, you use the helper as such: 如果您想检查当前用户是否有会话并且已登录,则使用帮助程序:

if user_signed_in?

which is essentially the same statement as: 这基本上与以下内容相同:

if !current_user.nil? && current_user.signed_in

If you'd like to check if a user object is signed in, then you call this: (where user is a User Model Object) 如果您想检查用户对象是否已登录,则将其称为:(其中user是用户模型对象)

if user.signed_in?

I'm not the author of Devise, but from what I can tell of Warden / Devise neither keep track of who is logged in. 我不是Devise的作者,但据我所知,Warden / Devise既没有记录谁登录。

The problem with having an is_online column in the User table is that it is difficult to see who is active on the website. 在User表中使用is_online列的问题是很难看到谁在网站上处于活动状态。 I would add a column to your User model called last_seen as a date-time, and update that with Devise every time the user requests a page. 我会在您的User模型中添加一个名为last_seen的列作为日期时间,并在每次用户请求页面时使用Devise更新该列。 You could then easily add a User.online_count method or also see if a user has been seen at the website in the last 5 minutes. 然后,您可以轻松添加User.online_count方法,或者查看用户是否在过去5分钟内在网站上看到过。

在routes.rb中使用devise_for :user

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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