Created
May 9, 2020 07:25
-
-
Save muhammadyana/c0d4974d5ec2cf40eb750d613c2bcd70 to your computer and use it in GitHub Desktop.
Ruby on Rails Soft Deleteable
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 | |
scope :deleted, ->{ where.not(deleted_at: nil) } | |
scope :without_deleted, ->{ where(deleted_at: nil) } | |
scope :with_deleted, ->{ unscope(where: :deleted_at) } | |
default_scope { without_deleted } | |
end | |
def destroy(mode=:soft) | |
if mode == :hard | |
super() | |
else | |
update(deleted_at: Time.zone.now) | |
end | |
end | |
def restore! | |
update!(deleted_at: nil) | |
end | |
def deleted? | |
deleted_at? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment