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

前端 未结 4 929
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 12:05

Here\'s what I\'d like to do:

class A {
  String string
  static constraints = {
    string(maxSize:100)
  }
}

class B extends A {
  static constraints = {
         


        
相关标签:
4条回答
  • 2021-01-01 12:23

    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).

    0 讨论(0)
  • 2021-01-01 12:28

    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.

    0 讨论(0)
  • 2021-01-01 12:29

    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

    0 讨论(0)
  • 2021-01-01 12:36

    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()
      } 
    }
    
    0 讨论(0)
提交回复
热议问题