When trying to persist a User object that has a many-to-many relation with a Role object i am getting unexpected behaviour. This at least to my newbie understanding.
Using a form that submits the User params and trying to persist the user a strange thing occurs. The validation errors on the User object which are there are totally ignored and the User object is persisted.
Example:
I have created a User domain class which has a constraint on the firstname [it may not be blank] and email [must be an email adress].
So i expect when the form params are submited to the controller the .save() or .validate() will complain when i submit a user with NO firstname and NO email.
But what is see in the database is that the user is persisted without any problems. Also the row in the ROLE_USERS table is nicely filled with the correct id's from the role and user.
My GSP create page submits the value's to the controller like this:
..Code:<g:textField name="firstname" value="${user?.firstname}" size="12"/>
and for the role data:
I checked the object details using NetBeans debugger and they inspectors tells me that indeed the User object is filled with a blank username, blank email and with a correct role inside it.Code:<g:select name="roles" from="${roles}" value="${user?.roles?.id}" optionKey="id" optionValue="name"/>
The controller takes the submitted data like this:
I did put in the vresult variable to indicate if the validation fails yes or no. When the User has incorrect data is gives false! so that is ok! Still the user.save() method persists the User domain object, despite having validation errors!!!Code:def save = { def user = new User(params) def vresult = user.validate() if(user.save(flush:true)) { render "ok" } else { render(view:'create', model: [user:user, roles: Role.list()]) } }
I also checked if a incorrect User is saved when there is no many-to-many mapping. So i have a single User object. Then the validation errors are correctly handled. In other words the User is then not persisted as I expect.
I am having this problem on Grails 1.3.1 and also 1.3.2
I am wondering what i am missing in this scenario?? Do I need to persist the data in another way? or am I using the many-to-many in a wrong way?
Code:class Role { String name String description static constraints = { name(blank:false, unique:true) description(nullable:true) } static hasMany = [users: User] } class User { String firstname String lastname String email String fogbugzToken static constraints = { firstname(blank:false) //email(email:true) } static hasMany = [roles: Role] static belongsTo = Role } class UserController { ... def save = { def user = new User(params) def bresult = user.validate() if(user.save(flush:true)) { render "ok" } else { render(view:'create', model: [user:user, roles: Role.list()]) } } ... }


Reply With Quote
