2014-10-07 76 views
0

Hi和因为现在感谢无法通过beforeInsert事件

改变域类布尔属性在域类我想基于使用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运行的应用程序,我得到在控制台下面的错误信息在那里我得到的消息,财产状况不能为空

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

我试了没有博olean属性和beforeInsert运行良好,我甚至创建了另一个项目来复制场景和相同的行为。

我所缺少的,我使用的Grails 2.3.8

感谢

回答

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,常规将返回boolean值。如果这是错误的,它将取消你的保存。您可能想要返回true或非false的内容以避免取消。

def beforeInsert() { 
    status = (type == "Dog") 
    true 
    } 
+0

感谢您的答案Alidad,但即使我从beforeInsert返回true,我也会得到相同的错误消息。我将所有类型的属性设置为Dog in bootstrap中的对象,以便始终将状态设置为true,但不成功 – user615274 2014-10-08 15:37:01