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?
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?
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]
}
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.