Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display last logged in details using Devise in Rails 3

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

like image 759
dannymcc Avatar asked Feb 23 '11 12:02

dannymcc


1 Answers

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.

like image 120
Brett Bender Avatar answered Sep 21 '22 01:09

Brett Bender