2016-09-28 106 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了,裏面回調的方法進行邏輯