ActiveRecord Transaction Explained

ActiveRecord provides you with the transaction mechanism. It allows you to ensure that while transaction executes, all of the commands will commit successfully or the will be rolled back if any of the transactions fail.

In order to set up ActiveRecord with transactions, you need to include active_record/transactions in your code. Adding records to many-to-many relationship table may be a good example of using transactions in ActiveRecord. In this example, we need to update entity table as well as relationship table and ensure that both tables are updated. If one update fails then entire update is rolled back to its original state.

Example of ActiveRecord transaction is presented below

class MyClass
 def my_method
  transaction do
   author = Person.create(:name=>”James”)
   ceate(:author => [author], :title => “My Title”
  end
 end
end

You can see from the example above that we create author first and then a record with the author object. However, if our main create fails then author object creation will be rolled back by ActiveRecord.

ActiveRecord transactions utilizes native transactions of the target database type. ActiveRecord transaction is versatile enough to restore not only database to prior state but also object’s variables. 

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…