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!
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::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
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.
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.
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
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