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?
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
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.
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.
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.
The account model inherits from ActiveRecord::Base so both are actually the same methods.
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