Here I am facing an unusual issue. Everything should work in my understanding (as a grails beginner), but not working 🙁
I have a domain class User. User can have many friends and many friendRequests. There is a function in domain class to send friend request to other user. here is the code from User Domain –
static hasMany = [friends: User, friendRequests: FriendRequest]
static mappedBy = [friendRequests:'receiver']
def sendFriendRequest(User toUser) {
if(!isFriend(toUser)) {
FriendRequest requestToSend = new FriendRequest(status:'pending', sender: this)
toUser.addToFriendRequests(requestToSend)
return true
}
return false
}
And the FriendRequest class is –
class FriendRequest {
String status
User sender
static constraints = {
status(inList:["accepted", "pending", "rejected"])
}
static belongsTo = [receiver:User]
}
Now, The problem is, I am expecting the current User object, from which I am running the function will be set as sender of friendRequest. But strangely the toUser, which I m passing as param is being set as sender!
Can anyone please explain what I am missing?
The
addToFriendRequestsmethod is overriding sender. It thinks thatFriendRequest.senderis the inverse ofUser.friendRequestsYour
FriendRequestclass will need two references toUser: one for the sender, and one for the receiver. You’ll also need to tell gorm which one maps back to thefriendRequestsrelationship. You can do this with a mapping in yourUserclass: