grails - How to set unique hasMany relations based class properties? -


i have 2 domain classes:

class book {   string name    static hasmany = [articles: article] }      class article {   string name    static belongsto = [book: book] }    

i want validate book have unique articals in terms of article name property. in other words: there must no article same name in same book. how can ensure that?

you can custom validator on book class (see documentation).

a possible implementation can this:

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

in example using java.util.set check duplicate names (set.add() returns false if same name added twice).

you can trigger validation of object mybookinstance.validate().


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -