Anis
Anis

Reputation: 3599

How can I set reference of a Domain class from inside itself in Grails?

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?

Upvotes: 1

Views: 415

Answers (1)

ataylor
ataylor

Reputation: 66059

The addToFriendRequests method is overriding sender. It thinks that FriendRequest.sender is the inverse of User.friendRequests

Your FriendRequest class will need two references to User: one for the sender, and one for the receiver. You'll also need to tell gorm which one maps back to the friendRequests relationship. You can do this with a mapping in your User class:

static mappedBy = [friendRequests:'receiver']

Upvotes: 1

Related Questions