Search code examples
grailsgrails-ormgrails-2.0grails-domain-class

How can I set a unique constraint per class instance?


Assume the user class:

class User {
  String name

  hasMany = [books: Book]

}

and the book class:

class Book {

  String name

  belongsTo = [user: User]

}

I want that the name of a book is unique per user. I.e., user1 can have books with name: [bookname1, bookname2] but he cannot have two books with the same name: [bookname1, bookname2]

User2 can also have books with name: [bookname1, bookname2] but not two books with the same name.

How can I restrict that the booknames are unique for each user?


Solution

  • Read the docs: http://grails.org/doc/latest/ref/Constraints/unique.html

    class Book {
    
      String name
    
      belongsTo = [user: User]
    
      static constraints = {
          name unique: 'user'
      }
    
    }