【问题标题】:Transaction Action with Ruby On Rails使用 Ruby On Rails 的事务操作
【发布时间】:2009-06-01 05:56:06
【问题描述】:

我在控制器内部有一个复杂的操作,它对数据库执行多个更新查询。

如何在不进行任何结构重构的情况下使此操作像事务处理

【问题讨论】:

    标签: ruby-on-rails transactions actioncontroller


    【解决方案1】:
    MyModel.transaction do
      begin
        @model.update_stuff
        @sub_model.update_stuff
        @sub_sub_model.update_stuff
      rescue ActiveRecord::StatementInvalid # or whatever 
        # rollback is automatic, but if you want to do something additional, 
        # add it here
      end
    end
    

    这里是the docs for the transaction method

    【讨论】:

      【解决方案2】:

      可以通过以下方式使控制器中的所有操作同时进行事务处理:

      around_filter :transactional
      
      def transactional
        ActiveRecord::Base.transaction do
          yield
        end
      end
      

      【讨论】:

      • 面向方面的编程。 Ruby有什么不能做的吗? (除了在 Windows 上工作。)
      猜你喜欢
      • 1970-01-01
      • 2010-12-29
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多