how to add uniqueness in rails migration
To add uniqueness in a Rails migration using Ruby, follow these steps:
- In the migration file, use the
add_index
method to create a unique index on the table. Specify the column name and the optionunique: true
to enforce uniqueness.
class AddUniqueConstraintToTableName < ActiveRecord::Migration
def change
add_index :table_name, :column_name, unique: true
end
end
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.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.