7

I have username column on users table. I could do somethig like this: rails generate migration add_username_to_users username:string:uniq but I have got username column (and I've already run migration).

So how can I make username column unique?

Jensky
  • 919
  • 3
  • 12
  • 26

2 Answers2

16

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.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
3

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
Evmorov
  • 1,134
  • 22
  • 28