我有一个ActiveRecord课程约会:
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?无论如何要知道如果被摧毁了怎么样?我用这里示范?
提前致谢
Eki
答案 0 :(得分: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
答案 1 :(得分: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