在 1.2 版本中,Grails 引入了全局约束。我尝试将以下内容添加到 Config.groovy
grails.gorm.default = {
constraints {
notBlank(nullable:false, blank:false)
}
}
然后在我的一个域类中使用它
static constraints = {
email(email: true, unique: true, shared: 'notBlank')
}
但是,当我保存电子邮件地址为空的用户时,没有报告任何错误,为什么?
谢谢,
大学教师
我从未尝试过创建全局约束,但我可以告诉您,如果您想将字段标记为非空白且不可为空,则根本不需要创建新约束,只需将其添加到您的域类中即可:
static constraints = {
email(blank:false)
}
当然,如果您期望保存时出现异常,则不会出现异常 - 您需要在调用 save() 或 validate() 后测试对象,如该域类中所示:
class Contact {
static constraints = {
name(blank:false)
}
String name
}
及其测试用例:
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
我发现它在开发中非常有用。
HTH
PS
要使用您定义的约束,您需要将其添加到您的域类中:
static constraints = {
email(shared:"myConstraintName")
}
但请注意,您无法像在内置测试中那样在单元测试中测试约束,因为配置不会被读取。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)