开发者

Using acts_as_paranoid plugin for soft delete - what about validations?

开发者 https://www.devze.com 2023-02-10 05:25 出处:网络
I am loo开发者_高级运维king on trying to use acts_as_paranoid plugin for soft delete of records. I was earlier managing it using a flag in the db. I know that this plugin will omit a record from searc

I am loo开发者_高级运维king on trying to use acts_as_paranoid plugin for soft delete of records. I was earlier managing it using a flag in the db. I know that this plugin will omit a record from searches and finds if the record is soft deleted. What I want to know is if I have a validation in the model like validates_uniqueness_of :email and I deleted(soft deleted) the record having email 'prince@gmail.com'. Now when I try to create a new user having same email, will the validation work and prevents the creation of the new record. Or will it omit the soft deleted record as it does for finds? (I would like this to happen, of course.)


acts_as_paranoid does not reimplement validates_uniqueness_of, so if you have (soft) deleted a record with email 'prince@gmail.com' you cannot create a new record with the same email.

The easy fix for this is to add a scope to validates_uniqueness_of:

validates_uniqueness_of :email, :scope => :deleted_at

This way you can have any number of (soft) deleted records with email 'prince@gmail.com' and still create a new record with the same email.


From our testing, the patching that acts_as_paranoid does affect the deletes, so you would end up with two records. From most of the conversations around the web, this is probably what you expect.

In our case, we didn't want this. When we create another user with the same email, we want to "undelete" the first user, and we'd like the validations to hep us with this. Turns out that we couldn't figure out a way to do what we wanted. We ended up not using acts_as_paranoid in this case, but we are still considering going back.

We did find one patch that allowed passing in a flag to validations (:with_deleted => true), so that you could explicitly control this. This seems like a good idea, but we decided not to pursue it. Unfortunately this issue highlights that this approach is a bit of a "leaky abstraction" and has to be used with care.


if yor are using "rails3_acts_as_paranoid" then have provision for above mentioned issue,

ActiveRecord's built-in uniqueness validation does not account for records deleted by ActsAsParanoid. If you want to check for uniqueness among non-deleted records only, use the macro validates_as_paranoid in your model. Then, instead of using validates_uniqueness_of, use validates_uniqueness_of_without_deleted. This will keep deleted records from counting against the uniqueness check.

Need to specify following way ,

acts_as_paranoid
validates_as_paranoid
validates_uniqueness_of_without_deleted :name
0

精彩评论

暂无评论...
验证码 换一张
取 消