Transaction class method of Active Record

Today I’m working on my rails project at work as usual, and met with a scenario that needs me to update a model by deleting and saving it in one go. So I learned that there is  a way of doing it by using the transaction class method from ActiveRecord.

It is very simple to use, you simply need to place the desired active record functions as a block argument into the transaction method like such:

Account.transaction do!!

By using this way, SQL statements will only become permanent if they can all succeed as one atomic action, so it is safe to make a series of active record interactions without worrying that it will fail half way, and left you in an undetermined and hard-to-debug state.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s