Вопрос

In a Grails 2.3.4 application I have a domain class representing relation between the author and articles. It contains three attributes:

  • type id (representing author (1), viewer (3) and other types)
  • member
  • article

-

class Article {
  static hasMany = [ relations: ArticleRelation ]

  string title
}

class ArticleRelation {
  static belongsTo = [ article: Article ]

  int    type
  Member member
}

Some of the types semantically shall not allow to create more than one pair of type+author. For example:

  • each article is allowed to have only one author

Other type+author don't have that restrictions. For example: viewer.

I was looking for a validation method in the domain class that would guarantee uniqueness of type+author pairs based on the value of the type.

Something like:

static constraints = {
    member unique: if (type == 1 || type == 2)
}

Is it possible to write such a constraint in Grails domain class?

--EDIT--

In fact, I discovered that the condition needs to be written differently: type+article need to be unique pair to describe the contains properly.

So the constraint in ArticleRelation would be

static constraints = {
  article validator: { val, obj ->
    if ((obj.type == 1) || (obj.type == 2)) {
      if (ArticleRelation.countByArticleAndType(val, obj.type) > 0) return ['myNotUniqueErrorKey']
    }
  }
}
Это было полезно?

Решение

You will need to write your own custom validator implementation for this. Lucky for you Grails exposes a way to do so. The documentation for validation shows some basic implementations and the last one is most applicable to your situation since you will need to reference other properties of the instance.

Your implementation may look something like this (just off the top of my head):

static constraints = {
  member validator: { val, obj ->
    if ((obj.type == 1) || (obj.type == 2)) {
      if (ArticleRelation.countByMemberAndType(val, obj.type) > 0) return ['myNotUniqueErrorKey']
    }
  }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top