Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: What's the difference between ActiveRecord::Base.transaction and MyClass.transaction?

I'm looking at the docs here http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

One example it gives is:

ActiveRecord::Base.transaction do
  david.withdrawal(100)
  mary.deposit(100)
end

Another example in the docs is:

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

What's the difference between the Base's method and the Account's method?

like image 533
Mirror318 Avatar asked Nov 03 '16 22:11

Mirror318


People also ask

What is ActiveRecord base?

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

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 does ActiveRecord :: Base transaction do?

ActiveRecord's transaction method takes a block, and will only execute the block and write to your database if no exceptions are raised. You can defined the transaction method on any class that inherits from ActiveRecord::Base , and that transaction will open up a single new database connection.

What is ActiveRecord base transaction in rails?

Transactions in ActiveRecordEvery database operation that happens inside that block will be sent to the database as a transaction. If any kind of unhandled error happens inside the block, the transaction will be aborted, and no changes will be made to the DB.


1 Answers

The account model inherits from ActiveRecord::Base so both are actually the same methods.

like image 168
quazar Avatar answered Oct 26 '22 23:10

quazar