问题描述
我在 users
表上有 username
列.我可以这样做:rails generate migration add_username_to_users username:string:uniq
但我有 username
列(而且我已经运行了迁移).
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).
那么如何使 username
列唯一?
So how can I make username
column unique?
推荐答案
不清楚是要确保 username
中的值是唯一的,还是要过滤现有值独一无二.
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
请注意,如果当前数据库中有重复项,创建将失败.在这种情况下,首先转到 CLI 并删除重复项,然后运行迁移.
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.
这篇关于使现有列在 Rails 中唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!