2014-02-15 67 views
0

我有一個ActiveRecord類預約:確定哪個回調負責在Rails中觸發事件? after_save或before_destroy觸發回調?

class Appointment < ActiveRecord::Base 
    after_save :send_notifications 
    before_destroy :send_notifications 

    protected: 

    def send_notifications 
    if destroyed? 
     logger.info "Destroyed" 
    else 
     logger.info "Confirmed" 
    end 
    end 
end 

現在的問題是,我試圖找到一種方法來確定哪些回調負責觸發send_notification的? after_save或before_destroy?無論如何知道如果被摧毀是多麼的喜歡?我在這裏用於示範?

在此先感謝

回答

1

我不知道你能不能告訴在這個階段,你是否要破壞或保存對象。

雖然您可以稍稍不同地調用回調來捕獲該信息。例如:

after_save do |appointment| 
    appointment.send_notifications(:saving) 
end 
before_destroy do |appointment| 
    appointment.send_notifications(:destroying) 
end 

protected 

def send_notifications(because) 
    if because == :destroying 
    log.info("Destroyed") 
    else 
    log.info("Confirmed") 
    end 
end 
1

如果你想在這兩個回調不同的行爲,我建議你通過不同的方法分發:

class Appointment < ActiveRecord::Base 
    after_save :send_notifications_on_save 
    before_destroy :send_notifications_on_destroy 

    protected 

    def send_notifications_on_save 
    send_notifications('Confirmed') 
    end 

    def send_notifications_on_destroy 
    send_notifications('Destroyed') 
    end 

    def send_notifications(message) 
    logger.info message 
    end 
end