Ruby on Rails事物嵌套具体方法应用解析
参考地址:http://www.verydemo.com/demo_c119_i6715.html
....................................................................
- Ruby监控网络发送断开警告信息
- 总结各种Ruby on Rails命令
- 轻松掌握Ruby on Rails上传图片实现技巧
- 几点常识让你知道Ruby优点
- Ruby关闭IE进程采用直接关闭进程法
首先看 transaction 方法
- ActiveRecord::Transactions
Public Class methods - # File vendor/rails/acti
verecord/lib/active_record/
transactions.rb, line 187 - 187: def transaction(&block)
- 188: self.class.transaction(&block)
- 189: end
可以看出他是调用类方法,类方法代码如下:
- # File vendor/rails/activerecord/lib/
active_record/transactions.rb, line 75 - def transaction(&block)
- increment_open_transactions
- begin
- #connection is kind of MysqlAdapter
- connection.transaction(Thread.current
['start_db_transaction'], &block) - ensure
- decrement_open_transactions
- end
- end
- #connection.transaction call method in
- # File vendor/rails/activerecord/
lib/active_record/connection_
adapters/abstract/database_
statements.rb, line 58 - # Wrap a block in a transaction.
Returns result of block. - def transaction(start_db_transaction = true)
- transaction_open = false
- begin
- if block_given?
- if start_db_transaction
- begin_db_transaction
- transaction_open = true
- end
- yield
- end
- rescue Exception =>
database_transaction_rollback - if transaction_open
- transaction_open = false
- rollback_db_transaction
- end
- raise unless database_transaction
_rollback.is_a? ActiveRecord::Rollback - end
- ensure
- if transaction_open
- begin
- commit_db_transaction
- rescue Exception => database
_transaction_rollback - rollback_db_transaction
- raise
- end
- end
- end
上面的代码即实现了rails中的transaction,可见ActiveRecord是不支持Ruby on Rails事物嵌套的。 如果模型使用的是相同的数据库, 那么用 ModelA.transaction 或 ModelB.transaction的作用是一样的。
- Code
- objecta.transaction do
- objectb.save!
- end
或者
- objectb.transaction do
- objecta.save!
- end
或者
- ModelA.transaction do
- objectb.save!
- end
都是一样的!
这些对象的方面或类方面, 到最后都是转换成SQL,让数据库来执行, 如果明白这个,一切都变得简单了!
就从SQL而言 "model.transaction do" 只是执行 Begin, "end" 执行Commit. 对于MYSQL个别是引挚支持的存储点功能不在本文讨论范围之内。补充一下, 目前只是SQLServer支持Ruby on Rails事物嵌套,所以如果说ROR支持事务嵌套也就有点勉强!
【责任编辑:曹凯 TEL:(010)68476606】
原文:Ruby on Rails事物嵌套具体方法应用解析 返回开发首页
相关推荐
何志文 2020-05-11
JOO 2020-04-26
yohunl 2008-01-11
wujiajax 2011-07-22
samllQ的备忘录 2011-07-22
wl00 2020-10-28
EricNet 2020-07-05
EricNet 2020-05-27
happyfreeangel 2020-04-09
Poisedflw 2020-03-23
yangliuhbhd 2020-03-06
Ben的程序员生涯 2013-06-01
chenshuixian 2013-06-01
wes0 2014-05-31
mrice00 2019-12-20
EricNet 2019-12-11
89304896 2019-12-08