Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord Transaction vs Class Transaction

I have a doubt about Rails Transaction type. What the diffence between them and whem to use each one ?

Active Record Transactions

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

Class Transactions

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

Instance Transactions

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

Thank you very much in advance!

like image 821
Alessandro Moreira Avatar asked May 29 '17 17:05

Alessandro Moreira


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 in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module...

How do I rollback a transaction in rails?

You roll back the transaction by raising the ActiveRecord::Rollback error, but the error isn't raised outside, as happens with other errors. Keep this behavior in mind and use it wisely.


1 Answers

AR Transaction is the Class Transaction

Account < ActiveRecord::Base
end

Account.transaction(block) == ActiveRecord::Base.transaction(block)

http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html https://apidock.com/rails/ActiveRecord/Transactions/ClassMethods/transaction

Instance Transaction is a convenience method

The instance method of DB transactions is a convenience method for more syntactically beautiful code.

You could do this instead.

account = Account.find(1)
ActiveRecord::Base.transaction do
  account.save!
end

And it would be the same for any of the above. Either way, it's generating SQL code in a transaction.

The proof is in the source code of the instance method for transactions.

# File activerecord/lib/active_record/transactions.rb, line 276
def transaction(options = {}, &block)
  self.class.transaction(options, &block)
end

https://apidock.com/rails/v4.2.7/ActiveRecord/Transactions/transaction

like image 170
fbelanger Avatar answered Oct 11 '22 01:10

fbelanger