Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique constraint issue paranoia gem

I have a rails app in which i am using devise and paranoia gems.
I have a users table in postgres db which has unique validation on email column. I am using paranoia for soft delete, issue is when i delete a user and then tey to create a user using the email of the deleted user it throws an error PG::UniqueViolation: ERROR.
I have read about this and know that this could be solved using partial index feature of rails.

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

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

How do i implement this?
Sorry for bad formatting, typing from mobile.

like image 242
Swapnil Devesh Avatar asked Oct 19 '22 02:10

Swapnil Devesh


2 Answers

Because you deleted user as soft delete so that email didn't remove from database, only an user attribute is_deleted was set to true.

To resolve PG::UniqueViolation: ERROR now you have to create unique index on both field email and deleted_at So your migration will be

class AddUniqueIndexToUsers < ActiveRecord::Migration
  def change
    remove_index :users, column: :email
    add_index :users, [:email, :deleted_at], unique: true
  end
end
like image 138
Rakesh Patidar Avatar answered Oct 28 '22 16:10

Rakesh Patidar


It will fail on Postgresql, possible solution will be

class AddUniqueIndexToUsers < ActiveRecord::Migration
  def change
    remove_index :users, column: :email
    add_index :users, [:email, :deleted_at], unique: true, where: "deleted_at is null"
  end
end

Refer https://www.ironin.it/blog/partial-unique-indexes-in-postgresql-and-rails.html

like image 40
Vishal Zambre Avatar answered Oct 28 '22 15:10

Vishal Zambre