无法通过 beforeInsert 事件更改域类中的布尔属性

问题描述 投票:0回答:1

我有这个域类:

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
看起来没问题。

代码有什么问题,如何修复?

grails
1个回答
0
投票

根据定义,如果最后返回 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
  }
© www.soinside.com 2019 - 2024. All rights reserved.