Display last logged in details using Devise in Rai

2020-03-03 08:05发布

I have a Rails 3 application and it's using Devise for the authentication.

I would like to display the date and time each user last logged in within the administration table of users.

I have based the application on the following application:

https://github.com/dannymcc/rails3-base

I have read through the Devise GitHub wiki and notice that it mentions that user events are trackable, but I can't find any information regarding accessing the information etc.

Any help/advice would be greatly appreciated!

Thanks,

Danny

2条回答
倾城 Initia
2楼-- · 2020-03-03 08:29

Instead of user.last_sign_in_at use current_user.sign_in_at as you want the last sign in details of user logged in.

查看更多
姐就是有狂的资本
3楼-- · 2020-03-03 08:38

The Devise documentation outlines the trackable module which will do what you want. In your user model, include the :trackable module like so:

  devise :database_authenticatable, 
      ...
      :trackable

And make sure your database has the right fields. Not sure how do this if you already have a user table, but adding fields with the right names and types should do the trick. My migration to create my users table looks like so:

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :name
      t.string :email

      t.database_authenticatable :null => false
      t.recoverable
      t.rememberable
      t.trackable

      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end

The t.trackable will add the correct fields. In my user model, they're as follows:

sign_in_count: integer, 
current_sign_in_at: timestamp, 
last_sign_in_at: timestamp, 
current_sign_in_ip: string, 
last_sign_in_ip: string

Then you can just do user.last_sign_in_at and check the strftime documentation on how to output the time in the format you want.

查看更多
登录 后发表回答