How do I add trackable to an existing Devise setup?
Asked Answered
D

1

16

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?

Dight answered 27/10, 2018 at 16:53 Comment(0)
D
41

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.

Diastyle answered 27/10, 2018 at 18:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.