2013-10-30 21 views
2

在表单提交后,我需要做一些处理,最终将多个记录保存在多个表中。因为我需要它全部或全无,所以我将它包装在一个事务块中。该块似乎工作得很好,但我不知道如何检查交易是否成功,以便我可以返回适当的响应。检查多插入事务是否成功

... 

     # Start a transaction block so we can back out if anything fails 
     ActiveRecord::Base.transaction do 

     # Journal Entry for from_account 
     gle = from_account.gl_journal_entries.create(....) 

     # Journal Line (x2) 
     gle.gl_journal_lines.create(....) 
     gle.gl_journal_lines.create(....) 


     # Journal Entry for to_account 
     gle = to_account.gl_journal_entries.create(....) 

     # Journal Line (x2) 
     gle.gl_journal_lines.create(....) 
     gle.gl_journal_lines.create(....) 

     end 

     # return something based on success/failure of transaction 

    ... 

回答

4

一个选项是捕捉它可能会或可能不会抛出的错误。在这种情况下:

def my_method 

    ... 

    ActiveRecord::Base.transaction do 
    # Journal Entry for from_account 
    gle = from_account.gl_journal_entries.create!(....) 

    # Journal Line (x2) 
    gle.gl_journal_lines.create!(....) 
    gle.gl_journal_lines.create!(....) 


    # Journal Entry for to_account 
    gle = to_account.gl_journal_entries.create!(....) 

    # Journal Line (x2) 
    gle.gl_journal_lines.create!(....) 
    gle.gl_journal_lines.create!(....) 
    end 

    # this code will only get executed if the transaction succeeds 

rescue Exception => ex 

    # this code will only get executed if the transaction fails 

end 

编辑:使用create!,而不是create在这种情况下,建议,因为如果有什么不顺心就会抛出一个错误。

+1

请注意,ActiveRecord :: Rollback异常不会在块外引发。但其他例外情况。所以也许用'create!' –

+0

PhilipHallstrom是正确的,编辑来反映。 – kddeisz

+0

这工作很好。感谢你们两位! –