I have a complex action inside controller that performs several update queries to the database.
How can I make this action acts like transaction without any structural refactoring?
What Is A Transaction? Transactions are typically used when you need to ensure data integrity, even if your web app crashes in the middle of a request. Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action.
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.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
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.
MyModel.transaction do
begin
@model.update_stuff
@sub_model.update_stuff
@sub_sub_model.update_stuff
rescue ActiveRecord::StatementInvalid # or whatever
# rollback is automatic, but if you want to do something additional,
# add it here
end
end
Here are the docs for the transaction method.
It's posible to make all actions in controller transactional at once with:
around_filter :transactional
def transactional
ActiveRecord::Base.transaction do
yield
end
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