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

标签 ruby-on-rails psql

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

相关文章:

whitespace - psql 查询返回在指定值的开头/结尾包含空格的值

sql - psql 的\dt 模式如何工作?

python-3.x - PostgreSQL repmgr 将查询发送到哪里

ruby-on-rails - 缺少重定向网址。在 Devise_token_auth 中的忘记密码中

html - 遍历 Rails 对象和数组

Django 和 Postgis : How can I create a spatial table with CONSTRAINT enforce_geotype_geom in Django?

php - 在 PHP 中导出 PSQL 表

ruby-on-rails - Rails 回调在不同环境下表现不同

ruby-on-rails - RSpec2 错误代码测试

ruby-on-rails - Rails 中的 respond_to 和 respond_with 有什么区别?