title: Grails data binding with one-to-many relationship - link back to parent is lost
body: <p>In a Grails 2.2.2 application, I have a one-to-many relationship that looks something like this:</p>
  
  <p>Parent:</p>
  
  <pre><code>class Client {
      ...
      String name
      static hasMany = [modelFieldInstances: ModelFieldInstance]
      ...
  }
  </code></pre>
  
  <p>Child:</p>
  
  <pre><code>class ModelFieldInstance {
      ...
      String name
      String value
      static belongsTo = [client: Client]
      ...
  }
  </code></pre>
  
  <p>I'm trying to create a data importer so that users can import a spreadsheet or csv containing their client records. To do this, I inspected the parameters that grails scaffolding uses when it creates a new <code>Client</code> instance in the <code>save</code> method of the standard scaffolding controller.</p>
  
  <p>The problem is that when I try to create and save a new <code>Client</code> instance with my importer, the child <code>ModelFieldInstance</code>s are saved without their reference to the parent <code>Client</code> (the <code>Client</code> and the <code>ModelFieldInstance</code>s all get persisted though).</p>
  
  <p>In my importer, I'm doing the data binding like this:</p>
  
  <pre><code>Client client = new Client()
  client.modelFieldInstances = ListUtils.lazyList(new ArrayList(), {new ModelFieldInstance()} as org.apache.commons.collections.Factory)
  client.properties = properties
  ...
  client.save()
  </code></pre>
  
  <p>I think the only real difference between how the Grails scaffolding controller works and how my importer works is that in my importer I'm initially setting the <code>modelFieldInstances</code> collection as a <code>LazyList</code>. However, before I added the <code>LazyList</code> assignment the data binding was blowing with an error like this:</p>
  
  <pre><code>Invalid property 'modelFieldInstances[31]' of bean class [com.myapp.Client]: Illegal attempt to get property 'modelFieldInstances' threw exception; nested exception is org.springframework.beans.InvalidPropertyException: Invalid property 'modelFieldInstances[31]' of bean class [com.myapp.Client]: Cannot get element with index 31 from Set of size 0, accessed using property path 'modelFieldInstances[31]'**
  </code></pre>
  
  <p>So, I guess the question is, why doesn't the data binding work in my data importer when I can see that it does work in the scaffolding controller for a given properties map.</p>