如何在grails域子类中添加对继承属性的约束

Jör*_*yer 23 grails inheritance constraints subclass command-objects

这是我想做的事情:

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

class B extends A {
  static constraints = {
    string(url:true)
  }
}
Run Code Online (Sandbox Code Playgroud)

所以A类应该有一些约束,B应该对同一个属性有相同的附加约束.

我无法让它工作,我可以想象它会与Table-per-Hierarchy概念发生冲突.

所以我尝试通过引入一个带有类B的约束的Command对象来解决这个问题,这些约束可以在类B的构造函数中进行验证.但似乎Command对象只能在控制器中使用(grails一直说没有.validate ()方法).

所以我的问题是:使用grails约束解决这个问题最优雅的方法是什么(不是手动重新实现验证)?可能...

  • 切换到每子类表概念?
  • 以某种方式使Command对象在Domain类中工作?
  • 还有其他方法吗?

编辑:我可以定义子类中的所有约束,重复父类的约束,或者根本不在父类中有约束.但是该解决方案应该适用于同一父类的多个子类(具有不同约束).

Rob*_*rMP 7

您可以使用

    class B extends A {
       static constraints = {
          importFrom A
          //B stuff
       }
    }
Run Code Online (Sandbox Code Playgroud)

作为http://grails.org/doc/latest/ref/Constraints/Usage.html中的


Vic*_*nko 5

它在2.x中的方式:

由于约束是由一些ConstraintsBuilder执行的闭包,我会尝试从B调用它,就像

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

  • @Artefacto - 您是否能够发布有效的答案,或编辑此答案以使其有效?我知道其他人有过这个问题.谢谢! (2认同)