独特的约束问题偏执宝石

SiD*_*esh 5 postgresql activerecord ruby-on-rails devise ruby-paranoia

我有一个 rails 应用程序,我在其中使用了 devise 和 paranoia gems。
我在 postgres db 中有一个用户表,它对电子邮件列进行了唯一验证。我正在使用偏执进行软删除,问题是当我删除用户然后使用已删除用户的电子邮件创建用户时会引发错误PG::UniqueViolation: ERROR
我已经阅读过相关内容,并且知道可以使用 rails 的部分索引功能来解决这个问题。

http://scottsmerchek.com/2015/08/03/taking-the-d-out-of-crud/

https://devcenter.heroku.com/articles/postgresql-indexes#partial-indexes

我该如何实施?
抱歉格式不正确,从手机打字。

Rak*_*dar 3

由于您以软删除方式删除了用户,因此电子邮件不会从数据库中删除,因此仅将用户属性is_deleted设置为 true。

要解决PG::UniqueViolation: ERROR现在的问题,您必须在字段电子邮件和deleted_at上创建唯一索引,因此您的迁移将是

class AddUniqueIndexToUsers < ActiveRecord::Migration
  def change
    remove_index :users, column: :email
    add_index :users, [:email, :deleted_at], unique: true
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 我使用以下迁移解决了这个问题: class `AddPartialIndexToUsers &lt; ActiveRecord::Migration def change remove_index :users, column: :email add_index :users, :email, unique: true, where: "deleted_at = NULL" add_index :users, : phoneno,unique:true,其中:“deleted_at = NULL”end end`这对我来说似乎更好,因为在您的迁移中我并不特别需要deleted_at是唯一的......这似乎更像是我所需要的......如果我在某处提到它是错误的,或者更新你的asnwer,这样我就可以接受它@Rakesh (5认同)