class User {
static constraints = {
password(unique:true, length:5..15, validator:{val, obj ->
if(val?.equalsIgnoreCase(obj.firstName)) {
return false
}
}
}
}
我发现这种时髦的语法真的令人困惑。我花了几天时间试图学习grails / groovy。我知道它的作用,但我真的不明白。
有人能解释一下这是如何运作的吗?
什么是约束?它是一个闭包,密码被称为函数吗? 怎么叫它?
验证器怎么样?
就像我说我能看到它的作用,我只是不明白它是如何做到的。
答案 0 :(得分:2)
前言 - 某些部分需要使用Groovy的基本知识。
//Domain Class
class User {
//A property of the domain class
//corresponding to a column in the table User.
String password
//Domain classes and Command objects are treated specially in Grails
//where they have the flexibility of validating the properties
//based on the constraints levied on them.
//Similar functionality can be achieved by a POGO class
//if it uses @Validateable transformation at the class level.
static constraints = {
//Constraints is a closure where validation of domain class
//properties are set which can be validated against when the domain class
//is saved or validate() is called explicitly.
//This is driven by AbstractConstraint and Constraint java class
//from grails-core
//Constraint on password field is set below.
//Here password is not treated as a method call
//but used to set the parameter name in the constraint class on which
//validation will be applied against. Refer AbstractConstraint
//for the same.
password(unique:true, size:5..15, validator:{val, obj ->
//Each of the key in the above map represents a constraint class
//by itself
//For example: size > SizeConstraint; validator > ValidatorConstraint
if(val?.equalsIgnoreCase(obj.firstName)) {
return false
}
}
}
}
上面提到了约束如何工作的基础知识。如果您需要了解更多细节,那么如果您对其使用有任何进一步的疑问,请务必访问以下一些来源:
显然,如果您遇到与约束相关的任何实施或更多,那么SO是提问的好地方。随意使用此社区来帮助您克服有问题的程序化情况。
答案 1 :(得分:0)
我有同样的问题,也无法找到Groovy书/文档中解释的语法。然后我谷歌找到这个博客:http://www.artima.com/weblogs/viewpost.jsp?thread=291467,它回答了我的问题。