4

I have a problem when trying to update an instance that has a field with constraint: unique, but has not been modified.

https://grails.github.io/grails-doc/latest/ref/Constraints/unique.html

class SectorEmpresarial{
    Long codigo
    String nombre

    static constraints = {
        nombre  nullable: false, size: 0..50, unique: true
    }
}

Example:

  1. Instance Created

    def sectorEmpresarialInstance = new SectorEmpresarial(codigo:1,nombre:"MY_NAME")
    sectorEmpresarialInstance.save(flush:true)
    
  2. Editing Instance (ERROR here)

    /* params=(codigo:2, nombre:"MY_NAME") look that nombre has not changed */

    def sectorEmpresarialInstance = SectorEmpresarial.findByCodigo(1)
    sectorEmpresarialInstance.properties = params 
    sectorEmpresarialInstance.save(flush:true) // Here present error because nombre has constraint: unique.
    
  • what problem do you have? any error, exception, or just don't know how to save it? – Igor Artamonov Jun 04 '15 at 14:08
  • You must first start with an object you retrieved from the DB in order to update it. If you use def a = SectorEmpresarial.findByNombre('somename'), then set a.codigo=10, then a.save(), the row should update. You can't just create a new instance, set the nombre to the same value, and expect it to update. You have to have a "database-connected" instance of SectorEmpresarial. – billjamesdev Jun 04 '15 at 14:33
  • I have somehow the same problem with Grails 3.0.9 and Grails 3.0.12. We have a domain class with a unique constraint and values are only updated if we change that field value. We are manually binding tha values instead of using .propeties = params. Is this a bug? If the unique constraint is deleted it works fine – Eylen Jan 27 '16 at 10:09

0 Answers0