Validate That a Grails hasMany Relationship Has At Least One Child

There are a lot of great validations built into Grails v1.1, but they are all focused on the object that is being validated. There are none that are capable of inspecting relationships. This is when we need to take advantage of the powerful custom validators that can be created with Grails. Here's an example of a simple case. I have a car class and I want to make sure that my car has at least one tire. < class="brush: groovy"> class Car { static hasMany[tires:Tire] static constraints = { tires(validator: { val, obj -> def retval = true if (!obj?.tires?.size()) { retval = 'car.validator.hasnotires.error' } return retval }) } } One tire a useful car does not make, though. We need four tires on our car. Let's tweak this to require exactly four tires. It's an easy change of just a few characters.
class Car {
  static hasMany[tires:Tire]
  static constraints = {
    tires(validator: { val, obj ->
      def retval = true
      if (!obj?.tires?.size() != 4) {
        retval = 'car.validator.haswrongtirecount.error'
      }
      return retval
    })
  }
}
It's easy to write similar validators that check for children of children, more detailed aspects of children, and so on. One more note. Although it may be obvious to some of you, it has tripped me up at least once. To save these data structures you must save them depth first. This means all children must be saved before you can save any parent object otherwise this validator will save since your children objects (your tires) will still be considered transient.