我想为列添加唯一约束 name
在现有表 psql 中
创建表(PostgreSQL):
class CreateRequests < ActiveRecord::Migration
def change
create_table :requests do |t|
t.integer :user_id
t.string :name
t.string :address
t.timestamps null: true
end
add_index :requests, :user_id
end
end
所以我在模型中添加了验证唯一性
class Request < ModelBase
belongs_to :user
validates :user, presence: true
validates :name, uniqueness: true, allow_blank: true
...
和这样的迁移:
def change
add_index :user_requests, :name, unique: true
end
但我注意到在某些情况下,名称可以为空,我可以在条件为
:name
的情况下添加索引吗?是否为空/不为空?编辑:是的,我希望那些空值保留在数据库中(我不需要修改过去的请求)。我认为我需要编辑迁移以更准确地了解数据库的实际状态。
最佳答案
没有人回答所以我要添加我的解决方案
迁移应该是这样的:
def change
add_index :user_requests, :name, unique: true, where: 'name IS NOT NULL'
end
(验证仍然:
validates :name, uniqueness: true, allow_blank: true
)
关于ruby-on-rails - Rails 迁移 - 添加允许跳过空值的唯一索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48112363/