Search code examples
grailsgrails-ormgrails-domain-class

Rules about relationships in a Domain Object


Is there such of a constraint that can validate relationships in a Domain object?

For example if you had a Meeting object with Participants and an Organization. Is there a way that you could make the Meeting contain a constraint that the Participants were a member of the Organization object?


Solution

  • Besides the fact you can author your own types of constraints, you also have the ability to write your own validation routines using validator. The Grails documentation covers a lot of the details but a quick example would be:

    class Meeting {
      static belongsTo = [org: Orginization]
      static hasMany = [partcipants: Person]
      ...
      static constraints {
        org(validator: {val, obj ->
          if (obj.partcipants.find{ it.org.id != val.id }) return 'some.message.code'
        })
      }
      ...
    }
    

    Keep in mind the above is off the top of my head (and I have a head cold) but it should point you in the right direction.