combining rollback in two action rails 4

108 views Asked by At

It is posible start a transaction in one action and excute a rollback in another? This is why I wanna do this:

I am making an application where the user can generate an order and that order can have multiple services so I have 2 models related Order and Service. There is a form with some radio buttons and textarea where the user is going to introduce the characteristics of the service and it have 2 submit buttons, one for add more services to that order and the second next. when the user click on next is going to be redirect to a page where he can see all the services and a button for save, if the user click on save then I wanna save the order and all services(5 services generate are 5 records on the table Service and one record on the table Order). But if the user start add services and in some point decide leave the page I don't wanna save anything.

I think this can be done with some sort of rollback or maybe there is another way.

1

There are 1 answers

0
Taryn East On

short answer: no not really.

Longer answer: transactions are, by their very definition atomic. They do what is to be done within them, then either commit or rollback.

you can't spread them over two server actions the way you are proposing, because by the end of the first action, the transaction must either commit or rollback... by the time the server gets the second action - either one or the other has already happened.

The way this is usually solved is to add a State to your order. eg a boolean column called "is committed" or something similar. The order can be created in a "not committed" state - and all your other actions only fetch and work with "committed" orders. If the user leaves the page, you can have a sweeper process clean up any uncommitted orders (ie delete them if a non-committed order is over 2 hours old).