title: Saving associated domain classes in Grails
body: <p>I'm struggling to get association right on Grails. Let's say I have two domain classes:</p>
  
  <pre><code>class Engine {
      String name
      int numberOfCylinders = 4
      static constraints = {
          name(blank:false, nullable:false)
          numberOfCylinders(range:4..8)
      }
  }
  
  class Car {
      int year
      String brand
      Engine engine = new Engine(name:"Default Engine")
      static constraints = {
          engine(nullable:false)
          brand(blank:false, nullable:false)
          year(nullable:false)
      }
  }
  </code></pre>
  
  <p>The idea is that users can create cars without creating an engine first, and those cars get a default engine. In the CarController I have:</p>
  
  <pre><code>def save = {
      def car = new Car(params)
      if(!car.hasErrors() &amp;&amp; car.save()){
          flash.message = "Car saved"
          redirect(action:index)
      }else{
          render(view:'create', model:[car:car])
      }
  }
  </code></pre>
  
  <p>When trying to save, I get a null value exception on the Car.engine field, so obviously the default engine is not created and saved. I tried to manually create the engine:</p>
  
  <pre><code>def save = {
      def car = new Car(params)
      car.engine = new Engine(name: "Default Engine")
      if(!car.hasErrors() &amp;&amp; car.save()){
          flash.message = "Car saved"
          redirect(action:index)
      }else{
          render(view:'create', model:[car:car])
      }
  }
  </code></pre>
  
  <p>Didn't work either. Is Grails not able to save associated classes? How could I implement such feature?</p>