Monocaffe
Grails hasMany Delete
Febrero 16th, 2011 - [Enlace local]
Suppose the following:
class Group{This means, you have lots of Users for some Group, but also a User might have other Groups, so can't use a "belongsTo". To delete a Group is really easy:
String name
static hasMany = [users:User]
}
class User{
String name
}
def b = Group.get(0)On the other hand, you might want to delete a User, but not the Group:
b.delete(flush:true)
def b = User.get(0)This will throw a lot of exceptions from Hibernate and JDBC. How are you supposed to do it? Well, first of all, you'll need a way to get a Group for a given User, but since "users" is transitive, you can't do something like Group.findByUser(user) so go ahead and add the following code to your Group class:
b.delete(flush:true)
static Group findByUser(User user){Now, go to your UserController delete method and add the following
def criteria = Group.createCriteria()
def result = criteria.get {
users {
idEq(user.id)
}
}
return result
}
if (userInstance) {The clear call will empty the references in the current object so you don't get any trouble.
try {
AlertGroup g = Group.findByUser(userInstance)
if(g){
g.users.remove(userInstance)
}
userInstance.delete(flush: true)
...