【问题标题】:“grails.validation.ValidationErrors: 0 errors” while saving a domain class保存域类时出现“grails.validation.ValidationErrors: 0 errors”
【发布时间】:2013-01-10 12:33:55
【问题描述】:

我有以下域类:

class StudentQuiz {
      Date dateCreated
      Date lastUpdated
      Quiz quiz
      float price
      Student student
      Date startTime
      Date endTime
      int score
      List answers
      static hasMany = [answers:Answer]
      static constraints = {
         answers nullable:true
      }

}

但是当我使用下面的代码来保存这个类的一个实例时:

 studentInstance =  (Student)User.findByEmailAndPassword(params.email, params.password.toString().encodeAsPassword())
 if (studentInstance) {
    StudentQuiz studentQuizInstance = new StudentQuiz(score:0,  quiz:quizInstance,price:quizInstance.price,student:studentInstance,startTime:new Date())
    if (!studentQuizInstance.save(flush:true)) {                    
      studentInstance.errors.each {
            println "===="+it+"-------"
        }
}

我得到了这个:

grails.validation.ValidationErrors: 0 errors

没有对错误的其他解释。任何帮助将不胜感激。

【问题讨论】:

    标签: validation grails groovy grails-domain-class


    【解决方案1】:

    您正在检查错误的实例。应该是这样的:

    if (!studentQuizInstance.save(flush:true)) {                    
        studentQuizInstance.errors.each {
        println "===="+it+"-------"
    }
    

    【讨论】:

    • 问题是,为什么 studentQuizInstance 没有保存,我已经在给定的代码中打印了错误
    • 您不会收到错误消息,因为在您的代码中域类从未得到验证。您是否尝试在 save() 之前使用 hasError 方法?也许您的参数列表与您的域类约束不匹配。
    • 不会 !studentQuizInstance.save(flush:true) 条件做同样的事情吗?和 studentInstance.errors.each { println "===="+it+"-------" } 会打印错误吗?
    • 是的,你是对的!见grails.org/doc/latest/ref/Domain%20Classes/save.html。 “如果验证失败并且实例未持久化,则保存方法返回 null,如果成功,则返回实例本身”。在保存调用期间验证失败时,错误对象中会出现错误。您尝试打印 studentInstance 的错误,但我应该是 studentQuizInstance。这就是解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2014-02-12
    • 2017-09-13
    • 1970-01-01
    • 2012-06-17
    • 2016-04-09
    • 1970-01-01
    相关资源
    最近更新 更多