[Ruby] [Rails] Implementation of validation that maintains uniqueness

less than 1 minute read

Tasks required to implement uniqueness validation

  1. Described on the application side (uniqueness: true)
  2. Described on the database side (unique: true)

Described on the application side

models/user.rb


validates :email, uniqueness: true

Described on the database side

$ rails g migration add_column_to_users

add_column_to_users.rb


def change
   add_index :users, :email, unique: true
end
$ rails db:migrate

In order to give uniqueness to table columns, index creation is also required. The reason is that by searching all the data, it is possible to confirm whether or not it is duplicated with the past data.