radar/paranoia — pull request #144 by hyoshida (2014-07-12 06:09:33+00:00)
Title: Destroy multiple records with flag_column and unique keys.

flag_column is a great idea.
However, I found that there is a problem with the case below.

---

1. Prepare a paranoia model with flag_column and unique keys.

```ruby
class AddDeletedAtToClients < ActiveRecord::Migration
def change
add_column :clients, :deleted_at, :datetime
add_column :clients, :is_deleted, :boolean, null: false, default: 0
add_index :clients, [:username, :is_deleted], unique: true
end
end
```

```ruby
class Client < ActiveRecord::Base
acts_as_paranoid :flag_column => :is_deleted
...
end
```

2. Create a record.
{ id: 1, username: 'bob', is_deleted: false }

3. Destroy the record.
{ id: 1, username: 'bob', is_deleted: true }

4. Create a new record with same username.
{ id: 2, username: 'bob', is_deleted: false }

5. Destroy the record. (SQL error)
{ id: 2, username: 'bob', is_deleted: true }

```ruby
#=> ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: columns username, is_deleted are not unique: UPDATE "clients" SET "is_deleted" = 1 WHERE "clients"."id" = 2
```

---

I suggest a modification that update flag_colum by primary key when destroy record for this problem.

1. Change flag_column type to `integer` from `boolean`.

```diff
- add_column :clients, :is_deleted, :boolean, null: false, default: 0
+ add_column :clients, :is_deleted, :integer, null: false, default: 0
```

2. Create a record.
{ id: 1, username: 'bob', is_deleted: 0 }

3. Destroy the record.
{ id: 1, username: 'bob', is_deleted: 1 }

4. Create a new record with same username.
{ id: 2, username: 'bob', is_deleted: 0 }

5. Destroy the record. (succeed)
{ id: 2, username: 'bob', is_deleted: 2 }

---

I hope that you would consider.

\# Please excuse my awful English...