Explicit soft deletion for ActiveRecord via deleted_at and default scope
Ruby
Latest commit d341cea Sep 21, 2017 @grosser thx for the fix
Permalink
Failed to load latest commit information.
gemfiles add test and docs for bad usecase Aug 8, 2017
lib v1.2.0 Sep 22, 2017
spec Make it work for AR version < 4 Sep 21, 2017
.travis.yml Compatibility with Rails 5.1 Apr 28, 2017
Gemfile wwtd Aug 27, 2015
Gemfile.lock
MIT-LICENSE add a MIT-LICENSE file, in case you do not know what it means or you … Jun 5, 2012
Rakefile wwtd Aug 27, 2015
Readme.md thx for the fix Sep 22, 2017
soft_deletion.gemspec add test and docs for bad usecase Aug 8, 2017

Readme.md

Explicit soft deletion for ActiveRecord via deleted_at + callbacks and optional default scope.
Not overwriting destroy or delete.

Install

gem install soft_deletion

Usage

require 'soft_deletion'

class User < ActiveRecord::Base
  has_soft_deletion default_scope: true

  before_soft_delete :validate_deletability # soft_delete stops if this returns false
  after_soft_delete :send_deletion_emails

  has_many :products
end

# soft delete them including all soft-deletable dependencies that are marked as :destroy, :delete_all, :nullify
user = User.first
user.products.count == 10
user.soft_delete!
user.deleted? # true

# use special with_deleted scope to find them ...
user.reload # ActiveRecord::RecordNotFound
User.with_deleted do
  user.reload # there it is ...
  user.products.count == 0
end

# Do NOT use on assocations: Account.first.users.with_deleted {

# soft undelete them all
user.soft_undelete!
user.products.count == 10

# soft delete many
User.soft_delete_all!(1,2,3,4)

TODO

  • nullify should use update_all on has_many on soft_delete (performance)
  • has_many :through should delete join associations on soft_delete
  • cascading soft_deletes should use the same timestamp for easy reverts

Authors

Contributors

Zendesk
michael@grosser.it
License: MIT
Build Status