Monday, February 6, 2017

Active record uniqueness validation with soft delete feature

Soft Delete:
   we will maintain the record with updating few flag to check whether its active or not deleted like active_flag.  We can update the same field again by updating the active_flag in future with some feature or some other mechanism

Hard Delete:
   We will remove the record without have a copy.


In one of my recent application, I have the requirement of validating uniqueness constraint with  soft delete feature. We have active_flag field to check whether the record is deleted or not. We have few gems to maintain this status. I have used  rails gem act_as_paranoid  to have in-build validation. In this case, we have deleted_at field to check the status of the record. This gem will update all the query to make sure this field has NULL value.

like,
Console:
    User.find(120)

It will run Query as follows:
   select `users.*` from users where `users.id` = 120 and `users.deleted_at` is NULL


In another case without using any gem, we need to write the custom validation to override this

in ../models/user.rb

validates :name, uniqueness: {scope: :active_flag, conditions: -> {where(active_flag: true)}, 'An Active user with same name already available' }


Note: There are many gems available for making soft delete feature. I have tried personally above act_as_paranoid. I am not sure about any other rails gem.

Hope this snippet helped to few folks.

Enjoy!!!



No comments:

Post a Comment