gpt4 book ai didi

ruby-on-rails - Rails 迁移 - 添加允许跳过空值的唯一索引

转载 作者:行者123 更新时间:2023-12-04 05:55:02 24 4
gpt4 key购买 nike

我想为列添加唯一约束 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com