Skip to content

Instantly share code, notes, and snippets.

@carlweis
Last active June 16, 2023 21:33
Show Gist options
  • Save carlweis/f971f9066e7909599fdaaa54cdd171cc to your computer and use it in GitHub Desktop.
Save carlweis/f971f9066e7909599fdaaa54cdd171cc to your computer and use it in GitHub Desktop.
Allows soft deletes of an active record model
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
@carlweis
Copy link
Author

carlweis commented Nov 1, 2017

Deletable

A rails concern to add soft deletes.

Usage

In your Tables add a boolean column is_deletable

class AddDeletedAtToUsers < ActiveRecord::Migration
  def change
    add_column :users, :deleted_at, :datetime
  end
end

In your models

class User < ActiveRecord::Base

  has_many :user_details, dependent: :destroy

  include SoftDeletable
end

Methods and callbacks available:

User.deleted
User.first.destroy
User.first.restore
User.first.restore(recursive: true)

NOTE By default deleted records are not returned unless you add them using the .deleted scope

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