title: Handling unsaved state of objects in grails
body: <p>I have a problem that probably is rather a design problem than a technical one.</p>
  
  <p>Assuming I have these classes:</p>
  
  <pre><code>class A {
      def someInfo
      static hasMany = [b: B]
  }
  
  class B {
      A a
      def info
      def moreInfo
      ...
      def aLotMoreInfo
  }
  </code></pre>
  
  <p>Now let's say the user is on a page where he can edit the b's of an A and he can add new b's. But the user needs to save his changes to A, otherwise everything will be discarded.</p>
  
  <p>My current approach is creating the additional b's, render them via AJAX and save their ID's in a session variable so I can delete the b's that are "unsaved".</p>
  
  <p>This works quite well but for one common use case:
  The user refreshes the page.</p>
  
  <p>I use the window.onunload-event to inform the user that he is going to lose his unsaved changes, and make an AJAX call to a delete function within it to delete the b's from the session-variable. 
  Unfortunately the index function of the A-controller is called before I have deleted the b's.
  This means, the "unsaved" b's are shown and shortly afterthat they'll be deleted which would force me to make a refresh or wait for the b's to be deleted somehow.</p>
  
  <p>Maybe the way I try to accomplish it is wrong anyway - in which case I'd be happy for any suggestions.</p>
  
  <p>So the question is: How to keep an eye on new objects that possibly could be discarded without the need to store every information of it in hidden fields to create them on the save-function?</p>
  
  <p><strong>Update:</strong></p>
  
  <p>I should have mentioned it before but I thought it is not that important.</p>
  
  <p>B is an abstract class which is extended by lots of classes such as the following example:</p>
  
  <pre><code>class childOfB extends B {
      def usefulExtraInfo
  }
  
  class anotherChildOfB extends B {
      def anotherUsefulExtraInfo
  }
  </code></pre>
  
  <p>Beside that B has an integer field that represents the position within the Set of b's in A. I know that I could use a SortedSet for that but for some specific reasons it has to be a separate field.
  I mention this because the view renders each of it as an element of a sortable list which could be reordered by drag&amp;drop.</p>
  
  <p>Use case: The user adds a few childOfB, anotherChildOfB and reorders them as he needs. How would I track the type of them without storing the type in the view, which would be bad practice as well, I think?</p>
  
  <p>Regards</p>