views:

35

answers:

2

Hi,

Please can you help with the example below:

class Car {

    static hasMany = [cd:Cd, fluffyDice:FluffyDice, wheel:Wheel]

}



class Wheel{

     static belongsTo = [car:Car]

}

How do I enforce that a car has at least one wheel?

A: 

this will force there to be at least one wheel or an exception will be thrown

class Car {
    List wheels
    static hasMany = [cds:Cd, fluffyDice:FluffyDice, wheels:Wheel]
}
Aaron Saunders
+1  A: 

You can use the minSize constraint. Note that you need to initialize the set. Ordinarily you don't - Grails does this for you - but the constraint doesn't fire for a null collection:

class Car {
   Set wheels = []
   static hasMany = [wheels: Wheel]
   static constraints = {
      wheels minSize: 1
   }
}

I renamed wheel to wheels since it's a set and the plural name is more natural, especially when adding elements, e.g. car.addToWheels(new Wheel(...)). But this has no effect on functionality.

Burt Beckwith