Prev | Current Page 540 | Next

Kevin Marshall, Chad Pytel, and Jon Yurek

"Pro Active Record: Databases with Ruby and Rails"


APPENDIX ?–  ACTIVE RECORD METHODS IN DETAIL 252
ActiveRecord::Transactions::ClassMethods
Public Instance Methods
transaction(*objects, &block)
This method executes all of the statements in the given block within an atomic action. An
atomic action is a group of operations that all must succeed in order for the action to be completed.
If one of the statements in the block fails (throws an exception), none of the statements
will take effect.
For example, when a user creates a new account in our computer system, their old
account is deleted; if we do not want to delete the previous account unless the creation of the
new account succeeds, we might wrap these two actions in a transaction, to ensure that they
are atomic:
old_account = Account.find(1)
Account.transaction do
new_account = Account.create(:last_name => old_account.last_name,
:first_name => old_account.first_name)
old_account.destroy()
end
In the preceding example, if either of the statements raises an exception, ROLLBACK will be
called on the database.


Pages:
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552