53

Suppose a simple Grails domain class:

class Account {
    String countryId;

    String userName;

    String password;

    static constraints = {
        ...???...
    }
}

It is required that user names are unique for a particular countryId, thus there must be a unique contraint on two columns. How to express this in the constraints definition?

rainer198
  • 3,195
  • 2
  • 27
  • 42
  • 4
    I was browsing the web and in particular stackoverflow without finding an answer. In the end, I found the solution in the [Grails reference](http://grails.org/doc/1.0.x/ref/Constraints/unique.html) although all other Grails documentation examples only contaning the single column case. Didn't know that self-answering is not allowed within 8 hours – rainer198 Sep 28 '11 at 12:46

1 Answers1

90
userName(unique: ['countryId'])

You can include as many other properties in the array that make up the other properties that must be considered in the "unique" constraint on the username.

So, for example if you wanted to make userName unique within a countryId and provinceId it would look like this:

userName(unique: ['countryId', 'provinceId']
Joshua Moore
  • 24,706
  • 6
  • 50
  • 73
  • 2
    In grails 3 it is written "userName unique: 'countryId'" http://docs.grails.org/latest/ref/Constraints/unique.html – Carlos Parraga Dec 21 '16 at 18:59
  • 5
    @CarlosParraga that's just a variant of the same thing. That same syntax can be used with versions of Grails prior to 3.x as well. – Joshua Moore Dec 22 '16 at 11:42