Skip to content

Instantly share code, notes, and snippets.

@greatghoul
Created August 15, 2014 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greatghoul/aee36893c97ad12c2878 to your computer and use it in GitHub Desktop.
Save greatghoul/aee36893c97ad12c2878 to your computer and use it in GitHub Desktop.
自定义 ActiveModelCallback
class Questionnaire < ActiveRecord::Base
include Restorable
set_callback :remove, :after, :after_remove
private
def after_remove
self.stop
end
end
module Restorable
include ActiveSupport::Callbacks
extend ActiveSupport::Concern
included do
define_callbacks :remove
define_callbacks :restore
default_scope -> { where(deleted_at: nil) }
scope :removed, -> { unscoped.where.not(deleted_at: nil) }
end
def remove
self.class.transaction do
run_callbacks :remove do
self.update_attributes(deleted_at: Time.now)
end
end
end
def restore
self.class.transaction do
run_callbacks :restore do
self.update_attributes(deleted_at: nil)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment