使现有列在Rails中唯一
我在users
表上有users
名列。 我可以像这样做一些事情: rails generate migration add_username_to_users username:string:uniq
但我有username
rails generate migration add_username_to_users username:string:uniq
(我已经运行了迁移)。
那么如何才能使用username
列独一无二?
如果您想确保username
中的值是唯一的,或者您希望将现有值过滤为唯一,则不是很清楚。
在数据库级别,确保唯一性的方式是通过索引。 在迁移中,为列创建新的唯一索引。
add_index :users, :username, unique: true
请注意,如果当前数据库中有重复项,则创建将失败。 在这种情况下,首先转到CLI并删除重复项,然后运行迁移。
你可以这样做:
add_index :table_name, :column_name, :unique => true
要么:
rails g migration add_index_to_column_name :column_name, :unique => true