Make existing column unique in Rails

It's not very clear if you want to ensure the values in username are unique, or if you want to filter existing values to be unique.

At database level, the way you ensure uniqueness is via indexes. In a migration, create a new unique index for the column.

add_index :users, :username, unique: true

Please note that the creation will fail if you have duplicates in the current database. In that case, first go to the CLI and remove the duplicates, then run the migration.


You can do like:

add_index :table_name, :column_name, :unique => true

Or:

rails g migration add_index_to_table_name :column_name, :unique => true