Question

I have the following:

GroupMember.groovy

public class GroupMember{
  String userName
  String role
}

GroupProfile.groovy

public class GroupProfile{
  List<GroupMember> groupMembers = new ArrayList<GroupMember>()
}

GroupProfileController.groovy

public class GroupProfileController{
  def createProfile{
    GroupMember groupOwner = new GroupMember()
    groupOwner.userName = "testUser"
    groupOwner.role = "OWNER"
    groupOwner.save()

    GroupProfile groupProfile = new GroupProfile()
    def members = grouProfile.groupMembers
    members.add(groupOwner)
    groupProfile.save()

    GroupProfile.list() //This list contains my GroupMember instance with the correct info
    redirecT(action: myProfiles)
  }

  def myProfiles={
    GroupProfile.list() //This list contains my groupProfile that I made but no GroupMember info
  }
}

My GroupProfile won't save my GroupMember info. How can I get my GroupProfile to save the GroupMember info?

Was it helpful?

Solution

The normal way to represent this relationship in grails would be:

public class GroupProfile {
    static hasMany = [groupMembers: GroupMember]
}

This will automatically generate a method on GroupProfile called addToGroupMembers that will create the associations. Saving the GroupProfile will also cascade to the group members, so you'll only need to call save once after adding the members.

Note that the groupMembers collection will actually be an instance of Set that doesn't necessarily preserve order. You can explicitly declare the collection as a List to preserve order, but it requires additional overhead including an extra database column, so make sure that's really what you want.

Check out the grails manual in the section on GORM: http://grails.org/doc/latest/guide/GORM.html

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