0

I have two domain classes:

class Book {
  String name

  static hasMany = [articles: Article]
}   


class Article {
  String name

  static belongsTo = [book: Book]
}   

I want to validate that a book does have only unique articals in terms of the article name property. In other words: there must be no article with the same name in the same book. How can I ensure that?

Michael
  • 32,527
  • 49
  • 210
  • 370

1 Answers1

1

You can do this with a custom validator on your Book class (see documentation).

A possible implementation can look like this:

static constraints = {
    articles validator: { articles, obj -> 
        Set names = new HashSet()
        for (Article article in articles) {
            if (!names.add(article.name)) {
                return false
            }
        }
        return true
    }
}

In this example I am using a java.util.Set to check for duplicate names (Set.add() returns false if the same name is added twice).

You can trigger the validation of an object with myBookInstance.validate().

micha
  • 47,774
  • 16
  • 73
  • 80