Search code examples
grailsgrails-orm

Grails - what happens with save() if validate on save is false and domain object is invalid?


What happens if I call save() on a domain object but have set validate: false?

if (!domainObject.save(validate: false)) {
    def errors = ""
    domainObject.errors.each {
        errors += it
    }
    throw new Exception("Error saving domainObject: ${errors}")
}

I had though that I would get an exception here as save would return null, but I have a test expecting an exception but it's failing, as none is thrown. If I turn on failOnError and don't turn off validate then the test performs as expected. What does the save() return if the object is invalid?


Solution

  • If you turn off validation for save, then the save is executed without validating the instance beforehand. This may or may not work due to constraints from the underlying database. However in the case where the instance gets persisted, then save will return the (persisted) object and this will not enter your if branch.

    If e.g. you have set blank: false or min: 6 in your domain object, and the underlying DB does not know about such constraints, then the save can be made perfectly fine.