ROR汇集---Transaction

Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically you should use transaction blocks whenever you have a number of statements that must be executed together or not at all. Example:









This example will only take money from David and give to Mary if neither withdrawal nor deposit raises an exception. Exceptions will force a ROLLBACK that returns the database to the state before the transaction was begun. Be aware, though, that the objects by default will not have their instance data returned to their pre-transactional state.


Different ActiveRecord classes in a single transaction

Though the transaction class method is called on some ActiveRecord class, the objects within the transaction block need not all be instances of that class. In this example a Balance record is transactionally saved even though transaction is called on the Account class:

 


Transactions are not distributed across database connections

A transaction acts on a single database connection. If you have multiple class-specific databases, the transaction will not protect interaction among them. One workaround is to begin a transaction on each class whose models you alter:









This is a poor solution, but full distributed transactions are beyond the scope of Active Record.


Save and destroy are automatically wrapped in a transaction

Both Base#save and Base#destroy come wrapped in a transaction that ensures that whatever you do in validations or callbacks will happen under the protected cover of a transaction . So you can use validations to check for values that the transaction depends on or you can raise exceptions in the callbacks to rollback.


Exception handling

Also have in mind that exceptions thrown within a transaction block will be propagated (after triggering the ROLLBACK), so you should be ready to catch those in your application code. One exception is the ActiveRecord::Rollback exception, which will trigger a ROLLBACK when raised, but not be re-raised by the transaction block.

Methods
Public Instance methods
transaction (&block)

以上内容转自:http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

关于多数据库访问的事务管理问题:

In an application I wrote for a client I needed transactions to handle a batch import of records from a legacy table into different models.

I browsed the documentation, googled for info and even asked in #rubyonrails, but wasn’t able to get any help, so I had to resort to good old trial and error.

First I tried nested transactions (the old way):




I had a couple of problems with this code:

  • Ugly
  • Deprecated

It also didn’t seem to work for me, so I banged my head against my laptop for half a hour or so and suddenly the rails documentation started to make sense, so I wrote this code instead:



The reason I used save! was that the documentation says that a transaction block catches exceptions. Unfortunately that’s not true and to make it work I had to remove the exclamation marks.

Now I had another problem. I included the transaction code in a class I put in lib/, ImportJob, and I was using it with script/runner:

 

 

All of a sudden I started getting method missing errors on transaction. Now I could investigate and do the right thing or just hack a solution – I decided to hack a solution :)



Deriving ImportJob from Migration solved my problems. Now if anyone has a cleaner solution I will be happy to implement it but at least I solved my problem with transactions (and I hope this will be helpful for someone else too).

Update: Tim pointed out some flaws in my code and some more testing revealed that I needed to have an exception to trigger a Rollback, so I modified the block:



This works fine, thanks Tim!

转自:http://tempe.st/2007/05/transaction-in-rails/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值