I have a form which spans multiple pages. The way it is set up now is not ideal because it saves (to the database) each page when it is submitted. So if the user does not complete the form across all pages there would be an incomplete user registration saved in the database.
I would like to 'rollback' the saves if the user doesn't fully fill in the form.
So is there a way to set up a transaction that would begin when the user fills out the first form and ends when the user finishes on the last page?
From the Rails API docs. Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa.
Rails now has support for multiple databases so you don't have to store your data all in one place. At this time the following features are supported: Multiple writer databases and a replica for each. Automatic connection switching for the model you're working with.
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.
Now ActiveRecord::Base. transaction is generally used when you want to create/update two or more unrelated objects in a single call. You want all of them to succeed else do nothing.
What you're looking for is the acts_as_state_machine gem. If you're unfamiliar with State Machines, take a look here.
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