Make existing column unique in Rails

旧巷老猫 提交于 2020-01-14 08:18:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!