MDA/MDD/TDD/DDD/DDDDDDD
posts - 536, comments - 111, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

rails事务

Posted on 2010-02-14 01:04 leekiang 阅读(826) 评论(0)  编辑  收藏 所属分类: ruby
1,around_filter进行action的自动事务处理
在controller里面可以使用around_filter来进行action的包装,当action中弹出异常的时候渲染一个特殊的出错 页面。将action代码包装在ActiveRecord::Base.transaction函数的block中执行,当引发异常后截获并重新抛出一个 ActiveRecord::Rollback异常让rails将数据回滚掉。ActiveRecord::Base.transaction对 ActiveRecord::Rollback异常处理后不会再将该异常往外面抛。

around_filter :around_action_filter
protected
def transaction
ret = true
ActiveRecord::Base.transaction do
begin
yield if block_given?
rescue Exception => ex
set_notice(ex.message)
ret = ex.message
raise ActiveRecord::Rollback, ex.message
end
end
return ret
end
def around_action_filter
return yield if request.get?
redirect_to(:controller => "error_display", :action => "error_notice") if 
transaction { yield if block_given? } != true
end

这里的transaction函数可以用在action里面作为手动事务处理的解决办法。
http://www.cgpad.com/SPAN/articles_show/940

只有注册用户登录后才能发表评论。


网站导航: