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!
失败并引发异常,那么一切都会回滚吗?
关于如何改进此代码的任何其他建议也是受欢迎的。
我要做的似乎是手动引发一个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