Skip to main content
 首页 » 编程设计

ruby-on-rails之使用 ActiveRecord 冒泡嵌套事务失败

2024年11月24日1952php

我在服务对象中有一个方法,该方法组合应包含在事务中的操作。其中一些操作也包含在事务中。例如:

class PostCreator 
   def create 
      ActiveRecord::Base.transaction do 
        post.do_this 
        post.do_that 
        user.do_more(post, other_stuff) 
      end 
   end 
 end 
 
 def Post 
   def do_this 
     transaction do; ...; end 
   end 
 end 

我需要任何嵌套的失败一直冒泡到顶部,但我不知道如何做到这一点,以及 nested transactions 上的 ActiveRecord 文档似乎没有提供解决方案。从文档:
# Standard nesting 
 
User.transaction do 
  User.create(username: 'Kotori') 
  User.transaction do 
    User.create(username: 'Nemu') 
    raise ActiveRecord::Rollback    #  This won't bubble up: 
                                    #  _Both_ users will still be created. 
  end 
end 
 
# Nesting with `requires_new: true` on the nested transaction 
 
User.transaction do 
  User.create(username: 'Kotori') 
  User.transaction(requires_new: true) do 
    User.create(username: 'Nemu') 
    raise ActiveRecord::Rollback    #  This won't bubble up either 
                                    #  "Kotori" will still be created. 
  end 
end 

请您参考如下方法:

以下是如何使嵌套事务中的失败冒泡:

User.transaction do 
  User.create(username: 'Kotori') 
  raise ActiveRecord::Rollback unless User.transaction(requires_new: true) do 
    User.create(username: 'Nemu') 
    raise ActiveRecord::Rollback 
  end 
end 

基本上,您必须在顶级事务中引发错误才能回滚。为此,如果嵌套事务返回假值(nil)或真值,则会引发错误。

希望有帮助!