我有以下代碼
ActiveRecord::Base.transaction do
begin
account.save
# outer statement
begin
user.save
# inner statement
rescue StandardError
raise ActiveRecord::Rollback
end
rescue StandardError
raise ActiveRecord::Rollback
end
end
如果'inner statement'出現例外,只有'user'會被回滾,對嗎?在這種情況下,“帳戶”不會回滾,不是嗎?
uj5u.com熱心網友回復:
在您的代碼中有一個資料庫事務,它是全有或全無的。回滾事務將回滾在該事務中所做的所有更改,無論您在何處發出回滾。
您也可以嵌套事務,但要注意默認事務會被壓縮在一起,因此即使您在第一個事務中添加第二個事務:
ActiveRecord::Base.transaction do
begin
account.save
# outer statement
ActiveRecord::Base.transaction do
begin
user.save
# inner statement
rescue StandardError
raise ActiveRecord::Rollback
end
end
rescue StandardError
raise ActiveRecord::Rollback
end
end
這仍然會導致單個事務,而回滾將取消所有更改。
要請求一個真正的子事務,您需要添加request_new: true到內部事務中:
ActiveRecord::Base.transaction do
begin
account.save
# outer statement
ActiveRecord::Base.transaction(require_new: true) do
begin
user.save
# inner statement
rescue StandardError
raise ActiveRecord::Rollback
end
end
rescue StandardError
raise ActiveRecord::Rollback
end
end
但是,目前唯一支持真正嵌套事務的資料庫是 MS-SQL。Rails 目前使用保存點來處理這個問題 - 所以不要被日志混淆。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/380716.html
