Skip to content

Instantly share code, notes, and snippets.

@songjiz
Last active March 31, 2021 03:53
Show Gist options
  • Save songjiz/b5422efa36914eb0ece630e07e61c8c9 to your computer and use it in GitHub Desktop.
Save songjiz/b5422efa36914eb0ece630e07e61c8c9 to your computer and use it in GitHub Desktop.
soft delete record
module SoftDelete
extend ActiveSupport::Concern
included do
scope :trashed, -> { where.not(deleted_at: nil) }
scope :not_trashed, -> { where(deleted_at: nil) }
scope :kept, -> { not_trashed }
define_model_callbacks :trash, :untrash
end
module ClassMethods
def trash_all
kept.each(&:trash)
end
def trash_all!
kept.each(&:trash!)
end
def untrash_all
trashed.each(&:untrash)
end
def untrash_all!
trashed.each(&:untrash!)
end
end
def trashed?
deleted_at?
end
def not_trashed?
!trashed?
end
alias kept? :not_trashed?
def trash
return false if trashed?
run_callbacks(:trash) do
update deleted_at: Time.current
end
end
def trash!
return false if trashed?
run_callbacks(:trash) do
update! deleted_at: Time.current
end
end
def untrash
return false if not_trashed?
run_callbacks(:untrash) do
update deleted_at: nil
end
end
def untrash!
return false if not_trashed?
run_callbacks(:untrash) do
update! deleted_at: nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment