问题
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?
回答1:
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.
回答2:
You can do like:
add_index :table_name, :column_name, :unique => true
Or:
rails g migration add_index_to_column_name :column_name, :unique => true
来源:https://stackoverflow.com/questions/33301597/make-existing-column-unique-in-rails