Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ridget/627d24be04a043589bfe to your computer and use it in GitHub Desktop.
Save ridget/627d24be04a043589bfe to your computer and use it in GitHub Desktop.
Trashable 'concern' for Rails models
# db/migrate/20120625030355_add_deleted_at_to_user.rb
class AddDeletedAtToUser < ActiveRecord::Migration
def change
add_column :users, :deleted_at, :datetime
end
end
# config/application.rb
module YourApp
class Application < Rails::Application
config.autoload_paths += %W(
#{config.root}/lib
#{config.root}/app/controllers/concerns
#{config.root}/app/models/concerns
)
end
# app/models/concerns/trashable.rb
module Trashable
extend ActiveSupport::Concern
module ClassMethods
def trashed
self.where.not(deleted_at: nil)
end
end
def trash
run_callbacks :destroy do
# Check if this is the timestamp you want to use
update_column :deleted_at, Time.zone.now
end
end
def recover
update_column :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