2016-09-28 130 views
1

我一直在试图调试代码一段时间没有成功...回调被触发两次

我有我的Order对象回调后的服务条款已同意向用户发送确认电子邮件电子邮件。有2种方式中,用户可以下订单:

  1. 用户的地方(create)的顺序,并同意当场
  2. 用户的地方(create)的订单,但等待的服务条款同意服务条款=>在以后的某个点用户同意服务条款(update

因此,我的回调代码如下所示:

class Order 
    include ActiveModel::Dirty 

    # for scenario 1 
    after_commit :email_alert, on: :create 

    #for scenario 2, executes only if agree_tos is changed because user could update other 
    #things about the order WITHOUT agreeing to terms. Also agree_tos_changed? is enough 
    #because it will only ever change to true, there's no nil or false option 
    after_save :email_alert, on: :update, if: :agree_tos_changed? 
end 

ActiveModel::Dirty工作正常,因为我有其他地方。无论如何,我目前的问题是,email_alert被触发两次。但我想不出为什么,因为代码似乎MECE够我...

+1

是否有这样的原因需要回调,而不是采取更接近呼叫站点的明确行动? –

+0

你可以尝试使用单行来创建/保存回调场景'after_commit:email_alert,:if =>:持久?' – sa77

回答

0

反正我目前的问题是,email_alert越来越 触发两次。

唯一的回调,有on选项有:

  • before_validation
  • after_commit

after_save没有这个选项,因此它是被解雇的保存(连同after_commit)。

您可以使用after_updatebefore_validationon: :update

但我会坐下来想办法,使这个单一的回调,有它before_validation了,里面回调的方法进行逻辑