Michael
Michael

Reputation: 33307

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?

Upvotes: 1

Views: 201

Answers (1)

James Kleeh
James Kleeh

Reputation: 12238

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

class Book {

  String name

  belongsTo = [user: User]

  static constraints = {
      name unique: 'user'
  }

}

Upvotes: 2

Related Questions