2013-02-19 45 views
2

我有一個情況我需要「do_this」「富」後,已成功創建和「do_that」當「do_this」已經沒有錯誤執行,就像這樣:使用事務around_create回調

class Foo < ActiveRecord::Base 

    around_create do |foo, block| 
    transaction do 
     block.call # invokes foo.save 

     do_this! 
     do_that! 
    end 
    end 

    protected 

    def do_this! 
    raise ActiveRecord::Rollback if something_fails 
    end 

    def do_that! 
    raise ActiveRecord::Rollback if something_else_fails 
    end 

end 

如果其中一個失敗,整個事務應該回滾。

然而,問題在於,即使'do_this'或'do_that'失敗,'foo'也會一直存在。是什麼賦予了?

回答

2

你不需要這樣做,如果你返回false到回調,它會觸發回滾。最簡單的方法來編寫你想要的是像這樣

after_save :do_this_and_that 

def do_this_and_that 
    do_this && do_that 
end 

def do_this 
    # just return false here if something fails. this way, 
    # it will trigger a rollback since do_this && do_that 
    # will be evaluated to false and do_that will not be called 
end 

def do_that 
    # also return false here if something fails to trigger 
    # a rollback 
end 
+0

所以你說,有沒有必要換一個事務塊裏面的任何代碼,成功地做錯誤回滾? – velu 2013-02-19 14:28:35

+1

是的,鐵軌爲你做 – jvnill 2013-02-19 14:37:39