Database transaction in Rails


Bookmark and Share

A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must exhibit four properties called the atomicity, consistency, isolation and durability (ACID) properties, to qualify as a transaction.

We use database transactions to make sure that all the instructions we send to database are successful, and would cause changes to the database only if they are successful. Let’s say that you are working on a banking application which would withdraw money from one account and deposit into another account. The code for it would look like below

But for some reason, the withdrawal was successful but the deposit was not, the amount was taken out but never deposited to the other user.To avoid these kind of issues, database has a functionality called transactions, in which you can  build up each sql query. But if for any reason, any of the sql statements fails or an exception rises in the block, all the transactions are rolled back to their original form.

In rails, the transaction method is available as class method and instance method, but the functionality for both is same. There is no difference when you will use.

and

The …

Read More

after_create vs after_save vs after_commit

after_save, after_create and after_commit are called active record call backs in rails. They get executed when we work on the database, similarly we also have before_* callback and callbacks on destroy as well. In this article I will explain you about the difference between *_save, *_create and *_commit callbacks.

The purpose of each as per rails docs:

after_create
Is called after Base.save on new objects that haven‘t been saved yet (no record exists)

after_save
Is called after Base.save (regardless of whether it‘s a create or update save)

after_commit
Is called after the database transaction is completed.

Now to explain the real difference between the three, we must first explain about database transaction. They are a protective block around a group of sql statements, that are permanent only if all of them succeed in a single atomic statement.

When rails execute a create, the after_save and after_create would be called within the transaction block of the create statement. So they will be executed before executing the sql statement to make permanent changes in the DB. If the query fails, then no change will happen to the DB, but we would have executed the instructions of the after_create and after_save block.

Where as after_commit, is called after the execution of the final/outer transaction block. Thus the changes in the DB would be permanent.

Read More