Rails 3交易,回滚一切

时间:2011-06-13 03:41:03

标签: ruby-on-rails-3 transactions

class Bear < ActiveRecord::Base
    def feed!
      self.transaction do
          raise Exception unless self.foods_eaten << Food.new(:name => "fish")
          self.fed_at = Time.now
          save!
       end
    end
end

class Hippo < ActiveRecord::Base
    def wash!
        self.transaction do
            @soap.inventory -= 1
            @soap.save!
            self.washed_at = Time.now
            save!
        end
    end
end

class ZookeeperController < ApplicationController

    def chores
        @zookeeper = Zookeeper.find(params[:id])
        Animal.transaction do
            begin
                @hippo.wash!
                @bear.feed!    # => FAIL AT THIS LINE
                @zookeeper.finished_at = Time.now
                @zookeeper.save!
                redirect_to chores_completed_path
            rescue Exception => e
                 render "new_chores"
            end
        end
    end
end

如果Zookeeper#chores被调用而@bear.feed!失败并引发异常,那么一切都会回滚吗?

欢迎任何其他有关如何改进此代码的建议。

1 个答案:

答案 0 :(得分:4)

似乎我要做的是手动引发ActiveRecord :: Rollback,否则它将无法按预期工作。 ActiveRecord :: Rollback是唯一不会导致屏幕转储的。 http://api.rubyonrails.org/classes/ActiveRecord/Rollback.html

它有意义,它会像这样工作,但并不是我直觉上认为它会起作用。如果我错了,请纠正我。

所以新代码看起来像这样:

class ZookeeperController < ApplicationController

    def chores
        @zookeeper = Zookeeper.find(params[:id])
        Animal.transaction do
            begin
                @hippo.wash!
                @bear.feed!    # => FAIL AT THIS LINE
                @zookeeper.finished_at = Time.now
                @zookeeper.save!
                redirect_to chores_completed_path
            rescue Exception => e
                 @_errors = true
                 render "new_chores"
            end
            raise ActiveRecord::Rollback if @_errors
        end
    end
end