Skip to content

Instantly share code, notes, and snippets.

@mankind
Forked from brianjlandau/soft_delete.rb
Created October 5, 2013 08:46
Show Gist options
  • Save mankind/6838460 to your computer and use it in GitHub Desktop.
Save mankind/6838460 to your computer and use it in GitHub Desktop.
This is a soft delete mixin for ActiveRecord 3.x. All you need to do is add a `deleted_at` column to the ActiveRecord models you mix this into.
module SoftDelete
extend ActiveSupport::Concern
included do
define_model_callbacks :soft_delete
define_model_callbacks :recover
default_scope where(:deleted_at => nil)
class_eval do
class << self
alias_method :with_deleted, :unscoped
end
end
end
module ClassMethods
def only_deleted
unscoped.where("#{table_name}.deleted_at IS NOT NULL")
end
end
def soft_delete
run_callbacks :soft_delete do
update_attribute(:deleted_at, Time.current)
end
end
def recover
run_callbacks :recover do
update_attribute(:deleted_at, nil)
end
end
end
@mankind
Copy link
Author

mankind commented Oct 5, 2013

Brian's response

It's adding all the standard callback functionality so that the run_callbacks calls inside of soft_delete and recover function properly. It allows you to define callbacks for those lifecycle events the same way you do for destroy and save and create and validate.

http://api.rubyonrails.org/classes/ActiveModel/Callbacks.html
https://github.com/goncalossilva/acts_as_paranoid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment