Topic: Multi-Model edit form with ajax and undo

In an edit-form for my Order model I want to be able to edit the order and assign new associations(order_items) to it. I do this using a small ajax form. After submitting the ajax-form to add stuff, the list of order_items nicely updates and the totals get updated too.

The problem arrives because I have save and cancel buttons on the screen.
Pressing cancel should also remove the added order_items, or re-add the ones that got deleted.
To be more precise: while on the edit-form, the changes should only get applied when the user clicks save, so adding and removing order_items should not instantly be applied.

The way I'm solving this right now is by keeping a clone of the model that's being edited in the session(I know this is very bad). I also keep an array of order_items in the session, because 'order << order_item' would otherwise instantly save the order_item. All in all it's becoming more and more hacky, so I want to change this behavior.

what would be (a|the) best way to solve this?

Re: Multi-Model edit form with ajax and undo

That's a tricky problem, and one I've been struggling with myself. What Ive ended up doing is keeping the state on the client. So rather than call the server and add items, I simply add items within the client (using some Javascript and hidden form trickery).

The advantage of this, is that I essentially end up with a single form that gets submitted, it's just that the form has been built dynamically on the client. As it's just a form, it looks and feels like a normal request from the server end ... and building elements is pretty easy ... you can either script the whole thing, or use AJAX to load out partials from the server.

The alternative of managing complex states on the server started breaking really fast - it's nasty and bug-prone.

Toby Hede
===================================================
FiniteStateMachine - Software Development for Social Networks
===================================================