Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save drench/8979935 to your computer and use it in GitHub Desktop.
Save drench/8979935 to your computer and use it in GitHub Desktop.
# db/migrate/20120625030355_add_deleted_at_to_user.rb
class AddDeletedAtToUser < ActiveRecord::Migration
def change
add_column :users, :deleted_at, :datetime
end
end
# app/models/concerns/trashable.rb
module Trashable
extend ActiveSupport::Concern
included do
default_scope { where(deleted_at: nil) }
end
module ClassMethods
def trashed
self.unscoped.where(self.arel_table[:deleted_at].not_eq(nil))
end
end
def destroy
run_callbacks :destroy do
update_column :deleted_at, Time.now
end
end
def recover
# update_column not appropriate here as it uses the default scope
update_attribute :deleted_at, nil
end
end
# app/models/user.rb
class User < ActiveRecord::Base
include Trashable
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment