当我获得验证失败时(发生异常后不刷新会话)错误消息,为什么?

时间:2012-03-11 01:25:41

标签: grails gorm

我有一个名为Project的域类:

class Project { 
        static hasMany = [ tasks : Tasks , users : User ] 
        static belongsTo = User 
        String name 
        static constraints = { 
                name(nullable:false,unique:true, size:5..20) 
                tasks(nullable:true) 
                users(nullable:true) 
        } 
        String toString() { 
                this.name 
        } 
} 

我使用以下代码保存Project个实例:

def save() { 
        def user = User.get(springSecurityService.principal.id) 
        def projectInstance = new Project(params) 
        projectInstance.addToUsers(user) 
        if (!projectInstance.save(flush: true)) { 
            render(view: "create", model: [projectInstance: projectInstance]) 
            return 
        } 
      flash.message = message(code: 'default.created.message', args: [message(code: 'project.label', default: 'Project'), projectInstance.id]) 
        redirect(action: "showCreatedProject", id: projectInstance.id) 
    } 

如果我提供Project name传递域类验证,则上述代码可以正常工作。但是,如果我将fail作为Project name(未通过域类验证),我会收到如下错误:

Message: null id in mnm.schedule.Project entry (don't flush the Session after an exception occurs) 
Trace:   Line | Method 
->> 886 | runTask in java.util.concurrent.ThreadPoolExecutor$Worker 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|   908 | run     in     '' 
^   662 | run . . in java.lang.Thread 

我对Grails很新,我不知道为什么会出现这个错误。我怎么能摆脱这个错误?

提前致谢。

1 个答案:

答案 0 :(得分:3)

addToUsers()需要已保存的对象,因为它需要填充ID来建立关系。您应该在.save()

之后调用此方法