Saving associated domain classes in Grails

Posted by Cesar on Stack Overflow See other posts from Stack Overflow or by Cesar
Published on 2009-06-25T03:14:37Z Indexed on 2010/04/30 4:47 UTC
Read the original article Hit count: 174

Filed under:
|
|
|

I'm struggling to get association right on Grails. Let's say I have two domain classes:

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)
    }
}

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:

def save = {
    def car = new Car(params)
    if(!car.hasErrors() && car.save()){
        flash.message = "Car saved"
        redirect(action:index)
    }else{
        render(view:'create', model:[car:car])
    }
}

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:

def save = {
    def car = new Car(params)
    car.engine = new Engine(name: "Default Engine")
    if(!car.hasErrors() && car.save()){
        flash.message = "Car saved"
        redirect(action:index)
    }else{
        render(view:'create', model:[car:car])
    }
}

Didn't work either. Is Grails not able to save associated classes? How could I implement such feature?

© Stack Overflow or respective owner

Related posts about groovy

Related posts about grails