Last active
June 16, 2023 21:33
-
-
Save carlweis/f971f9066e7909599fdaaa54cdd171cc to your computer and use it in GitHub Desktop.
Allows soft deletes of an active record model
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 SoftDeletable | |
extend ActiveSupport::Concern | |
included do | |
default_scope { where(deleted_at: nil) } | |
scope :deleted, -> { unscope(where: :deleted_at).where.not(deleted_at: nil) } | |
end | |
def delete | |
self.touch(:deleted_at) if has_attribute? :deleted_at | |
end | |
def destroy | |
callbacks_result = transaction do | |
run_callbacks(:destroy) do | |
delete | |
end | |
end | |
callbacks_result ? self : false | |
end | |
def self.include(klass) | |
klass.extend Callbacks | |
end | |
module Callbacks | |
def self.exteded(klass) | |
klass.define_callbacks :restore | |
klass.define_singleton_method("before_restore") do |*args, &block| | |
set_callback(:restore, :before, *args, &block) | |
end | |
klass.define_singleton_method("around_restore") do |*args, &block| | |
set_callback(:restore, :around, *args, &block) | |
end | |
klass.define_singleton_method("after_restore") do |*args, &block| | |
set_callback(:restore, :after, *args, &block) | |
end | |
end | |
end | |
def restore!(opts = {}) | |
self.class.transaction do | |
run_callbacks(:restore) do | |
update_column :deleted_at, nil | |
restore_associated_records if opts[:recursive] | |
end | |
end | |
self | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Deletable
A rails concern to add soft deletes.
Usage
In your Tables add a boolean column is_deletable
In your models
class User < ActiveRecord::Base
Methods and callbacks available:
NOTE By default deleted records are not returned unless you add them using the
.deleted
scope