Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ActiveRecord transaction block of instance and a class?

I am using Active Record Transactions in my current task. I was able to done my job in the both the ways I mentioned below. But I am not clear that there are any differences, calling transaction method on instance and class.

I have gone through the Rails API, but did not notice any differences.

What is the difference between following two usages of transaction method?

Account.transaction do
  balance.save!
  account.save!
end

balance.transaction do
  balance.save!
  account.save!
end

Thanks in advance!

like image 997
Venkat Ch Avatar asked Jul 09 '15 14:07

Venkat Ch


People also ask

What is an ActiveRecord transaction?

Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. Transactions are used to enforce the integrity of the database and guard the data against program errors or database break-downs.

What is ActiveRecord base?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

How do rails transactions work?

Rails transactions are tied to one database connectionAnd as long as the transaction block is running this one database connection is open. So try to do as little as needed inside the transaction block, otherwise you will be blocking a database connection for more time than you should.

How do you destroy in rails?

To create the controller action for the destroy-resource, we perform three substeps: (1) create an empty destroy-resource controller action, (2) add code to the action that retrieves the model object, and (3) add code to the action that destroys the model object and responds to the browser with an HTTP redirect.


1 Answers

There's no difference, the instance method simply delegates the execution to the class method. Here's the code:

def transaction(options = {}, &block)
  self.class.transaction(options, &block)
end
like image 120
mrodrigues Avatar answered Sep 22 '22 01:09

mrodrigues