2016-12-30 76 views
0

我想觸發相同功能after_commit兩個updatecreate但我想申請一個特定的條件update軌道4個after_commit嵌套條件問題

現在,我唯一的解決辦法是複製的功能,使兩種不同的after_commit這樣的:

after_commit :my_method_on_update, 
       on: :update, 
       if: ->(foo) { foo.previous_changes.key?(:bar) } 

after_commit :my_method_on_destroy, on: :destroy 

def my_method_on_update 
    # stuff 
end 

def my_method_on_destroy 
    # same stuff here 
end 

當然它的工作原理,但它不會使代碼DRY可言。我敢肯定有一個更好的解決方案,但我還沒有發現任何相關的例子在官方的軌道doc

我想什麼是這樣的:

after_commit :my_method, 
       on: :update, 
       if: ->(foo) { foo.previous_changes.key?(:bar) }, 
       on: destroy 

def my_method 
    # stuff 
end 

但有一個誤差兩次聲明on

回答

1

在大多數情況下,我會認爲兩個單獨的after_commit鉤子是更可取的 - 如果有很多共享代碼,您可以將它提取到第三個方法中,您可以從更新中調用並創建回調。但是,如果你真的需要把一切都在一個回調和一個方法,那麼你可以使用transaction_include_any_action?檢查記錄是否已創建或更新:

after_commit :my_method 

def my_method 
    # do shared stuff for both create and update 
    # ... 
    if transaction_include_any_action?([:update]) 
    # do stuff only for create 
    end 
end 

編輯

所以,據我所知,你希望回調在每個createupdate上運行,但如果動作爲update並且滿足某個條件,則不執行任何操作。你仍然可以使用transaction_include_any_action?,並簡單地使回調方法返回早期如果條件滿足,就像這樣:

after_commit :my_method, on: [:create, :update] 

def my_method 
    return true if transaction_include_any_action?([:update]) && previous_changes.key?(:bar) 
    # otherwise, continue 
    # ... 
end 
+0

您好,感謝你的快速回答和你的建議!但是,我不認爲你的技巧可以幫助我,因爲我需要在'create'或'update'上做同樣的事情。唯一的問題是,如果條件不能在'update'上完成,我就不會做任何事情。 –

+0

@MaxChrétien看到我的編輯 - 你可以讓這個方法不做任何事情!儘管說實話我仍然認爲有兩個'after_commit'掛鉤會更清晰。 – omnikron

+0

完美!你知道我是否可以將'if'條件放在'after_commit'的同一行嗎? –

0

基於@omnikron,這裏是我的自定義解決方案:

after_commit :my_method, 
       on: [:destroy, :update], 
       unless: :exclude_commit_hook 


    def exclude_commit_hook 
    transaction_include_any_action?([:update]) && foo.previous_changes.key?(:bar) 
    end 

    def my_method 
    # stuff 
    end 
+0

整潔!只有一件事,在你的情況下,如果應該運行提交鉤子,'should_run_commit_hook'方法實際上返回'false',所以命名有點混亂。您可以考慮將其更改爲'exclude_commit_hook'或其他內容以使其更清晰。 – omnikron

+0

我的確在我的真實代碼上應用了更好的命名,但我同意這裏有點混淆。 Thx再次幫助! –