2012-08-16 34 views
2

我遇到了Grails控制器內更新操作的問題。Grails bug?更新操作忽略rejectValue

當我提交一個密碼更改的表單(或其確認)時,我想要驗證它,如果它沒有得到很好的確認,我應該拒絕表單並警告用戶。我試圖按照這個Grails文檔說明(http://grails.org/doc/latest/ref/Domain%20Classes/errors.html)。

當我只更改密碼或確認時,一切正常。

但是,當我改變其他東西,然後在窗體中的密碼,即使驗證密碼的塊顯然很好地執行,對象(userInstance)仍然更新時,問題來了。而且,不僅其他數據是持久的,而且還是「不確定」的密碼。

我試圖在下面的示例代碼中插入一些'printlns'來說明會發生什麼。我正在使用Grails 2.0.0並在IntelliJ 11.1.3中進行調試(如果有幫助的話)。

我希望已經足夠清楚。

感謝您的任何答案。

def update() { 
    ... 

    if (params.password != params.confirmPassword) { 
     println("This message is correctly printed when passwords differ.") 
     userInstance.errors.rejectValue('password', 
             'defaut.password.diff.message', 
             'Password confirmation is incorrect!') 
     render(view: "edit", model: [userInstance: userInstance]) 
     return 
    } 

    println("This message is correctly NOT printed when passwords differ.") 
    println("But 'userInstance' object is updated in DB anyways. :(") 

    if (!userInstance.save(flush: true)) { 
     render(view: "edit", model: [userInstance: userInstance]) 
     return 
    } 

    flash.message = message(code: 'default.updated.message', args: [message(code: 'utilisateur.label', default: 'Utilisateur'), utilisateurInstance.id]) 
    redirect(action: "show", id: utilisateurInstance.id) 
} 

回答

4

我認爲您的userInstance是因爲成功操作後自動刷新保存的。如果密碼不匹配,請在返回語句前嘗試使用userInstance.discard()。這樣你就可以從Hibernate中分離出這個實例,並且在一個動作之後它不會被保存。

+0

Thanks Tomasz!這就是它。 – mateuscpf 2012-08-16 14:59:34