Posted on 2010-02-14 01:04
leekiang 閱讀(844)
評論(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