我有这个域类:
class Pet {
String name
String type
Boolean status = true
static constraints = {
name blank:false
type inList:["Dog", "Cat"]
}
def beforeInsert() {
status = (type == "Dog") ? true : false
}
String toString() { name }
}
我想使用
beforeInsert
事件根据条件更改布尔属性。
我尝试在
bootstrap.groovy
中创建一些测试数据:
class BootStrap {
def init = { servletContext ->
def nami = new Pet(name:"nami", type:"Dog")
if (!nami.save()) {
nami.errors.allErrors.each { error ->
log.error "[$error.field: $error.defaultMessage]"
}
}
def hotch = new Pet(name:"hotch", type:"Cat")
if (!hotch.save()) {
hotch.errors.allErrors.each { error ->
log.error "[$error.field: $error.defaultMessage]"
}
}
}
}
但是当我运行
grails run-app
(使用 grails 2.3.8)时,我收到此错误消息:
| Error 2014-10-07 13:27:28,281 [localhost-startStop-1] ERROR conf.BootStrap - [status: Property [{0}] of class [{1}] cannot be null]
| Error 2014-10-07 13:27:28,314 [localhost-startStop-1] ERROR conf.BootStrap - [status: Property [{0}] of class [{1}] cannot be null]
如果没有布尔属性,beforeInsert
看起来没问题。
代码有什么问题,如何修复?
根据定义,如果最后返回 false,
beforeInsert
将取消操作。
beforeInsert - Executed before an object is initially persisted to the database.
If you return false, the insert will be cancelled.
由于您的
beforeInsert
方法只有一行并且将状态设置为 true 或 false,因此 groovy 将返回该布尔值。如果这是错误的,它将取消你的保存。您可能希望返回 true 或 false 以外的其他值以避免取消。
def beforeInsert() {
status = (type == "Dog")
true
}