Question

I want to add a child to two different parent class, like that:

First:

class Member {
    Profile profile

    Member() {
        this.profile = new Profile()
    }

    static mapping = {
        profile cascade: 'all-delete-orphan'
    }
}

Second:

class Team {
    Profile profile

    Team() {
        this.profile = new Profile()
    }

    static mapping = {
        profile cascade: 'all-delete-orphan'
    }
}

Thw child is simply define like that

  class Profile() {
  }

The probleme is when I save the parent, it dosent save the child:

Member member = new Member().save(flush: true, failOnError: true)

assert !member.hasErrors()
assert member.profile           
assert !member.profile.hasErrors()

assert member.profile.id //FAIL

What do I do wrong? Is there a better way to do it?

UPDATE:

I found this

Saving associated domain classes in Grails

It seem that 'belong to' is needed for that kind of behavior. But Why the 'cascade: 'all-delete-orphan' doesn't force this ? Because I can't use 'belong to' in that specific case

Was it helpful?

Solution 2

I found a nice solution. The best was to define both parent in the child but nullable. Like that:

class Profile() {
    static belongsTo = [member: Member, team: Team]

    static constraints = {
        member nullable: true
        team nullable: true
    }
}

This way, the cascade behavior work just fine !

OTHER TIPS

I copied your example (with slight modification to change group table name to a non-reserved word) and the cascades are working properly using grails 2.2.1. Both Member and Group cascaded their saves to the newly created Profiles.

Assuming your classes are more complicated than this, you might have an error elsewhere in your class (eg cascade behavior described in constraints instead of mapping, etc).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top