-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
Brian, This is an awesome way to do Soft Deletes and was about to implement it but wasn't sure what the define_model_callbacks was actually doing in this example?