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/rail开发者_JAVA百科s3-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
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.
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.
Devise 2.0 or later (currently 4.0)
Devise 2.0 no longer includes helpers for your migrations. It means that you can no longer use the migration shorthand t.trackable
. Instead, you need to list the database fields explicitly.
Step by step, it goes like this.
- Create a new migration file with:
rails generate migration AddDeviseTrackableColumnsToUsers
- Edit your newly create file to include the following:
class AddDeviseTrackableColumnsToUsers < ActiveRecord::Migration[6.1]
def change
add_column :users, :sign_in_count, :integer, default: 0, null: false
add_column :users, :current_sign_in_at, :datetime
add_column :users, :last_sign_in_at, :datetime
add_column :users, :current_sign_in_ip, :string
add_column :users, :last_sign_in_ip, :string
end
end
- Run your migration:
rails db:migrate
- Finally, update your User model to activate trackable:
class User < ApplicationRecord
devise :database_authenticatable, :trackable
end
Now you should be able to use user.last_sign_in_at
without a problem
精彩评论