简体   繁体   中英

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? 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? 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. 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)

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.

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. 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. 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.

在routes.rb中使用devise_for :user

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