0

Im working on a simple user authentication system on Rails.

Due to this i'm adding a column to my users model to have an authentication token.

Reading resources online I should also apparently add an index to this authentication token. Can someone explain to me the purpose and rational of adding an index?

I understand it may have something to do with ensuring tokens are unique, but im do not understand how or what the index does. Below is my migration code

class AddAuthenticationTokenToUsers < ActiveRecord::Migration
  def change
    add_column :users, :auth_token, :string, default:""
    add_index :users, :auth_token, unique: true 
  end
end
Ian Go
  • 11

1 Answers1

0

You don't need authentication tokens to be unique (although if you generate them properly, it is very unlikely there will be duplicates). If you do want to enforce uniqueness, you should do it in your model with validates_uniqueness_of. This is subject to possible race conditions but should be fine for this.

I would not create an index as this will add needless overhead to your database.

steve klein
  • 2,566
  • 1
  • 14
  • 27