问题描述
这是我想要做的:
class A {
String string
static constraints = {
string(maxSize:100)
}
}
class B extends A {
static constraints = {
string(url:true)
}
}
所以类 A 应该有一些约束,而 B 应该对同一属性有相同的附加约束.
So class A should have some constraints and B should have the same plus additional constraints on the same property.
我无法让它工作,我可以想象它会与 Table-per-Hierarchy 概念发生冲突.
I couldn't get that to work though and I can imagine that it would clash with the Table-per-Hierarchy concept.
所以我试图通过引入一个带有 B 类约束的 Command 对象来解决这个问题,该约束可以在 B 类的构造函数中进行验证.然而,似乎 Command 对象只能在控制器中使用(grails 一直说有没有 .validate() 方法).
So I tried to work around that problem by introducing a Command object with class B's constraints which can be validated in the constructor of class B. However it seems that Command objects can only be used within controllers (grails keeps saying that there is no .validate() method for it).
所以我的问题是:使用 grails 约束(而不是手动重新实现验证)解决这个问题的最优雅的方法是什么?可能是...
So my question is: What is the most elegant way to solve this using grails constraints (not re-implementing the validation manually)? Could be...
- 切换到每个子类表的概念?
- 以某种方式使命令对象在域类中工作?
- 还有其他方法吗?
我可以在子类中定义所有约束,重复父类的约束,或者甚至在父类中根本没有约束.但是该解决方案应该适用于同一父类的多个子类(具有不同的约束).
It would be okay for me to define all the constraints in the child classes, repeating the constraints of the parent class or not even having constraints in the parent class at all. But the solution should work for multiple child classes (with different constraints) of the same parent class.
推荐答案
可以使用
class B extends A {
static constraints = {
importFrom A
//B stuff
}
}
如http://grails.org/doc/latest/ref/Constraints/Usage 中所述.html
这篇关于如何在 grails 域子类中对继承的属性添加约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!