2013-02-19 65 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