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!
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? 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.
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...
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With