How do I add trackable to an existing Devise setup?

Viewed 5141

Im trying to get the last sign in date time in RoR application using Devise gem. In one of my migration files I noticed the # t.datetime :last_sign_in_at field among others:

## Trackable
  # t.integer  :sign_in_count, default: 0, null: false
  # t.datetime :current_sign_in_at
  # t.datetime :last_sign_in_at
  # t.string   :current_sign_in_ip
  # t.string   :last_sign_in_ip

So the question is: how to activate this field for my users to be able to call it later in my app? Should I just uncomment that?

1 Answers

First, you need to generate a new migration:

rails generate migration AddDeviseTrackableColumnsToUsers \
sign_in_count:integer \
current_sign_in_at:datetime \
last_sign_in_at:datetime \
current_sign_in_ip:string \
last_sign_in_ip:string

then replace:

add_column :users, :sign_in_count, :integer

with:

add_column :users, :sign_in_count, :integer, default: 0, null: false

Now the migration file looks like:

class AddDeviseTrackableColumnsToUsers < ActiveRecord::Migration[5.2]
  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 rails db:migrate

In the user model app/models/user.rb, ensure that :trackable option is added to the devise method:

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :registerable, :recoverable, :rememberable, :validatable, :confirmable,
  # :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :trackable
end

The enabled options may be different in your case, just add :trackable if you didn't find it.

Now you can use last_sign_in_at attribute like other attributes.

Related