Sagarmichael
Sagarmichael

Reputation: 1624

Cannot remove from a list

I am trying to remove an object from a has many relationship. User has an object called guest, guest has a has many called children see bellow:

class User {

    transient springSecurityService

    String username
    String password
    String email
    boolean enabled
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired
    Guest guest
}

Guest:

class Guest {

    static hasMany = [children:Child]

    static constraints = {
    }
}

I use the following to add children:

User.guest.addToChildren(Child.get(params.id))

this works perfectly well. I cannot however do the following:

User.guest.removeFromChildren(Child.get(params.id))

I have also tried

Guest guest = User.guest
guest.removeFromChildren(Child.get(params.id))
guest.save(flush: true, failOnError: true)

With no success. I have also done appropriate checks to make sure that the child instance is contained in guest and it matches

Child.get(params.id)

Any ideas?

Upvotes: 0

Views: 97

Answers (1)

Gregg
Gregg

Reputation: 35864

The mystery part of your question is where are you getting User from? It could be that it is a detached instance which could be causing your issues. I would try the following:

Guest guest = User.guest.merge()  // make sure Guest has a hibernate context
Child child = Child.get(params)
guest.removeFromChildren(child)
// don't believe what the docs tell you
// I always have to delete the instance I am removing
// from the collection
child.delete()

And do this in a service method or surround it with a transaction closure.

Upvotes: 1

Related Questions