Archive for April, 2010

Deleting child entity from many-to-many in grails

Today, i spend entirely too long trying to delete a entity in grails. Turns out it’s terribly simple (of course), but i just got stuck, so now (maybe) i can help others get unstuck. Let’s say you have the following:

class Parent {
  static hasMany = [children:Child]

class Child {
  static hasMany = [parents:Parent]
  static belongsTo = Parent

If you want to delete a child element (but not delete the parent), you can’t just call delete!. This gives you a constraint exception. This makes sense enough. First, you need to remove all the associations between the parent and the child. Okay, so my next try was this:

child.parents.each { child.removeFromParents(it) }



Okay, so that didn’t work. This confused the heck out of me for a while, but then i finally found something that make sense: i was removing elements from the set that i was iterating over. Remember, all these associations are managed by hibernate, and when you call removeFrom, you are changing the collection. Here was my solution:

def tmp=[]
child.parents.each { tmp << it }
tmp.each { child.removeFromParents(it) }

And that worked like a charm. Anyone know a cleaner way to do this, or is this a recommended mechanism? The grails docs weren't totally clear on this.