Grails全局约束 [英] Grails global constraints
问题描述
grails.gorm.default = {
constraints {
notBlank(可为空,false,空:false)
}
}
然后在我的一个领域类中使用它$ / $>
static constraints = {
email(email:true, unique:true,shared:'notBlank')
}
但是当我保存一个用户有一个空的电子邮件地址,没有错误报告,为什么?
谢谢,
Don
我从来没有尝试过制定全局约束,但我可以告诉你,如果你想标记一个字段不是空白而不是空的,你不需要创建一个新的约束,只需将其添加到您的领域类:
static constraints = {
email(blank:false)
当然,如果您希望在保存时发生异常,您将无法获得一个 - 您需要在调用save()或validate()之后测试该对象,如本领域类所示:
class Contact {
static constraints = {
name(blank:false)
}
字符串名称
}
及其测试用例:
$ p $ import grails.test。*
class ContactTests extends GrailsUnitTestCase {
protected void setUp(){
super.setUp()
}
protected void tearDown(){
super.tearDown()
}
void testNameConstraintNotlable(){
mockDomain Contact
def contact = new Contact()
contact。 save()
assertTrue contact.hasErrors()
assertEqualsnullable,contact.errors [name]
}
}
如果您确实希望在保存时发生异常,您可以在Config.groovy中添加此设置:
grails.gor m.save.failOnError = true
我发现它在开发中非常有用。
HTH
PS
定义您需要将其添加到您的领域类:
static constraints = {
email(shared: myConstraintName)
}
但是请注意,你不能在单元测试就像你内置的那样,因为配置不会被读取。
In version 1.2, Grails introduced global constraints. I tried adding the following to Config.groovy
grails.gorm.default = {
constraints {
notBlank(nullable:false, blank:false)
}
}
Then using it in one of my domain classes
static constraints = {
email(email: true, unique: true, shared: 'notBlank')
}
But when I save a user with a null e-mail address, no errors are reported, why?
Thanks, Don
I've never tried to make global constraints, but I can tell you that if you want to mark a field as not blank and not nullable you don't need to create a new constraint at all, just add this to your domain class:
static constraints = {
email(blank:false)
}
Of course if you're expecting an exception on save you won't get one - you need to test the object after calling save() or validate() as demonstrated in this domain class:
class Contact {
static constraints = {
name(blank:false)
}
String name
}
and its test case:
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"]
}
}
If you do want exceptions on save, you can add this setting in your Config.groovy:
grails.gorm.save.failOnError = true
I found it to be quite useful in development.
HTH
PS
To use a constraint you've defined you'd need to add this to your domain class:
static constraints = {
email(shared:"myConstraintName")
}
But be warned, you can't test the constraint in a unit test as you would the built in ones as the config will not have been read.
这篇关于Grails全局约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!