goncalossilva/rails3_acts_as_paranoid — pull request #76 by dra1n (2012-09-12 12:43:52+00:00)
Title: Unique constraint

We have unique constraints in our database. They was broken when record was marked as deleted by ActsAsParanoid and we tried to create new one with same values of unique fields. I suggest to handle this situation by deleting old record.

Schema:

create_table :paranoid_with_unique_constraints do |t|
t.string :unique_field
t.string :arbitrary_field
t.datetime :deleted_at

t.timestamps
end
add_index :paranoid_with_unique_constraints, :unique_field, :unique => true

Model:

class ParanoidWithUniqueConstraint < ActiveRecord::Base
acts_as_paranoid
ensure_unique_constraint_on :unique_field
end

Test:

model = ParanoidWithUniqueConstraint.create(:unique_field => 'imoneandonly')
model.destroy

another = ParanoidWithUniqueConstraint.create(:unique_field => 'imoneandonly', :arbitrary_field => 'another')
another.persisted? # => true

another = ParanoidWithUniqueConstraint.find_by_unique_field('imoneandonly')
another.arbitrary_field # => 'another'