Search code examples
grails

I have an error when using custom id in grails


I want to have a custom id, since by default grails handles the id name. I have a domain class like this:

class User {
    Long id_user
    String name
...
    static mapping = {
        id generator: 'increment', name: "id_user", type: 'Long'
    }
...    
}

When I save a user I get the following error 'Can not redirect for object [project.User: (unsaved)] it is not a domain or has no identifier. Use an explicit redirect instead'in the save action

def save(User user) {
    if (user == null) {
        notFound()
        return
    }

    try {
        userService.save(user)
    } catch (ValidationException e) {
        respond usuario.errors, view:'create'
        return
    }

    request.withFormat {
        form multipartForm {
            flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), user.id])
            redirect user
        }
        '*' { respond user, [status: CREATED] }
    }
}

To correct the error I tried to put user.id user in save function but it did not work either.


Solution

  • Without building up a test case to reproduce this, it looks suspiciously like

    redirect user
    

    is attempting to redirect to /user/show/<user.id>, as the error message suggests, consider replacing this with

    redirect(action: 'show', params:[id:user.id_user])
    

    I'm not well-versed in custom ids, so I'm not sure of all the nuances, but the redirect shortcut you're using may not properly respect them.