How to add constraints on inherited properties in a grails domain sub-class

最后都变了- 提交于 2019-11-30 10:57:35

You can use

    class B extends A {
       static constraints = {
          importFrom A
          //B stuff
       }
    }

as states in http://grails.org/doc/latest/ref/Constraints/Usage.html

The way it was in 2.x:

As constraints is a closure executed by some ConstraintsBuilder, I'd try calling it from B, like

class B extends A { 
  static constraints = { 
    url(unique: true)
    A.constraints.delegate = delegate  # thanks Artefacto
    A.constraints()
  } 
}

Basically I do not see how it can be done.

Design wise a domain class actually maps the structure of the database table. The constraints will actually generate DB constraints. So your are trying to make several objects that will generate different constraints on the same table.

I think the better approach would be to create one domain object that has the simplest subset of constraints and then use different command objects to fine tune the exact constraints you want to be passed to the domain.

You could also use the validator: in the constraints to fine tune different constraints for different objects types (something like a types column in the domain and based on different types do different validation).

You need to redeclare the superclass constraints because it's a static clojure (static properties and static methods doesn't are inherited by child classes), so, it's not mapped by GORM.

Cheers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!