how to add uniqueness in rails migration

To add uniqueness in a Rails migration using Ruby, follow these steps:

  1. In the migration file, use the add_index method to create a unique index on the table. Specify the column name and the option unique: true to enforce uniqueness.
class AddUniqueConstraintToTableName < ActiveRecord::Migration
  def change
    add_index :table_name, :column_name, unique: true
  end
end
  1. Run the migration by executing the rails db:migrate command in the terminal. This will apply the unique constraint to the specified column in the database.

  2. Verify the uniqueness constraint by attempting to insert or update records in the table. The database will raise an error if a record violates the unique constraint, ensuring that only unique values are allowed in the specified column.