I have an Account class that has many managers (User class) & reps (User class).
class Account {
static hasMany = { reps: User, managers: User }
}
Then, I have a User class which belongs to an account. User is differentiated into manager or rep using a Role Enum inside User class.
class User {
static belongsTo = { account: Account }
Role role
}
The problem is, when I create a user of any type and save it, Grails ends up adding that user to both managers and reps sets in the account object.
I realize I need to use mapped_by here, however I don't understand how it should be used. The manager and rep is differentiated by a Role Enum inside User class.
I have looked at several stackoverflow questions #1, #2 however most of the times, problems get solved with other relationships.
I specifically want to use 2 one-to-many relationships between the Account and User class.
Edit : Code to initialize a rep:
def addRep(manager) {
User rep = new User( account: manager.account,
role: Role.REP)
rep.save(flush: true, failOnError: true)
}
You need to specify which association is to be used :
def addRep(manager) {
User rep = new User(role: Role.REP)
manager.account.addToReps(rep) // This will do the bi-association
rep.save(flush: true, failOnError: true)
}