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

时间:2014-10-07 19:43:47

标签: grails

嗨,现在谢谢

在Domain类中,我想基于使用beforeInsert事件的条件更改布尔属性,但布尔属性不受影响。这是域类:

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 }
}

我尝试在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之后我在控制台中收到以下错误消息,我收到的消息是属性状态不能为null

| 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 2.3.8

由于

1 个答案:

答案 0 :(得分:0)

根据定义,beforeInsert将在最后返回false时取消操作。

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
  }
相关问题