prabhap
prabhap

Reputation: 61

has one relationships and deletion in grails

How should I delete the child object in a hasOne relationship in grails for e.g.:

class Face {
 static hasOne = [nose: Nose]
}
class Nose {
 Face face
 static belongsTo= Face
}

I tried deleting the child object by two ways

1. face.nose.delete()
2. nose.delete()

I always get the same exception Deleted object resaved by cascade in both the ways. And one more do I have any dynamic methods (like addTo and removeFrom for hasMany) for hasOne? Any help?

Upvotes: 6

Views: 2412

Answers (3)

oreddo
oreddo

Reputation: 1

try this

noseId = face.nose.id
face.nose = null
nose.get(noseId).delete(flush:true)

Upvotes: -1

Daniel Engmann
Daniel Engmann

Reputation: 2850

You could try

face.nose = null
face.save()
nose.delete()

If you only delete nose then the property face.nose is still set. A later call of face.save() would resave the nose.

If you only set face.nose = null (without saving) then the change isn't saved to the database. A later query to the database to get a Face would give you a Face with the nose set and a save() would resave it.

Upvotes: 4

mh377
mh377

Reputation: 1836

Try making your class as follows:

class Face {
        Nose nose
}

class Nose {    
        static belongsTo = Face
}

Then to delete try:

def f = Face.get(1)
f.nose.delete()
f.delete()

Upvotes: 0

Related Questions