Created
August 15, 2014 00:29
-
-
Save greatghoul/aee36893c97ad12c2878 to your computer and use it in GitHub Desktop.
自定义 ActiveModelCallback
This file contains 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
class Questionnaire < ActiveRecord::Base | |
include Restorable | |
set_callback :remove, :after, :after_remove | |
private | |
def after_remove | |
self.stop | |
end | |
end |
This file contains 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 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