Grails全局约束
在版本1.2中,Grails引入了全局约束。我尝试将以下内容添加到Config.groovy中Grails全局约束,grails,gorm,Grails,Gorm,在版本1.2中,Grails引入了全局约束。我尝试将以下内容添加到Config.groovy中 grails.gorm.default = { constraints { notBlank(nullable:false, blank:false) } } 然后在我的一个域类中使用它 static constraints = { email(email: true, unique: true, shared: 'notBlank') } 但是,当我使用
grails.gorm.default = {
constraints {
notBlank(nullable:false, blank:false)
}
}
然后在我的一个域类中使用它
static constraints = {
email(email: true, unique: true, shared: 'notBlank')
}
但是,当我使用空电子邮件地址保存用户时,不会报告任何错误,为什么
谢谢,
不要我从未尝试过创建全局约束,但我可以告诉您,如果您想将字段标记为非空且不可为空,则根本不需要创建新约束,只需将其添加到域类中即可:
static constraints = {
email(blank:false)
}
class Contact {
static constraints = {
name(blank:false)
}
String name
}
static constraints = {
email(shared:"myConstraintName")
}
当然,如果您希望在保存时出现异常,则不会出现异常-您需要在调用save()或validate()后测试对象,如此域类中所示:
static constraints = {
email(blank:false)
}
class Contact {
static constraints = {
name(blank:false)
}
String name
}
static constraints = {
email(shared:"myConstraintName")
}
及其测试用例:
import grails.test.*
class ContactTests extends GrailsUnitTestCase {
protected void setUp() {
super.setUp()
}
protected void tearDown() {
super.tearDown()
}
void testNameConstraintNotNullable() {
mockDomain Contact
def contact = new Contact()
contact.save()
assertTrue contact.hasErrors()
assertEquals "nullable", contact.errors["name"]
}
}
如果确实希望保存时出现异常,可以在Config.groovy中添加此设置:
grails.gorm.save.failOnError = true
我发现它在开发中非常有用
嗯
PS
要使用已定义的约束,需要将其添加到域类中:
static constraints = {
email(blank:false)
}
class Contact {
static constraints = {
name(blank:false)
}
String name
}
static constraints = {
email(shared:"myConstraintName")
}
但请注意,您不能在单元测试中测试约束,因为您将无法读取配置中的内置约束。如果您希望将默认约束应用于所有属性,则应为:
grails.gorm.default = {
constraints {
'*'(nullable:false, blank:false)
}
}
如果要命名约束,可以使用shared键将其应用于电子邮件的域类属性:
static constraints = {
email(email: true, unique: true, shared: "notBlank")
}
grails中的默认值是不允许空属性,因此blank:false是您真正需要的(即,您在本例中定义的全局默认值是不需要的)。感谢您提供的关于无法对全局约束进行单元测试的提示-我不知道这一点。顺便说一句,你为什么不想在prod中也打开failOnError呢?我一直将其关闭,这样默认的行为是在日志文件中悄悄地失败,而不是在用户屏幕上吐出一个大堆栈跟踪。当然,还有其他方法可以实现这一点,而且你可能会设置自己的500错误屏幕,所以我想答案是个人偏好。