Nadav
Nadav

Reputation: 1185

Domain class hasMany fails to add entry

I'm a Grails noob so please excuse my noob question.
I've created a domain classes User and Device. User hasMany devices:Device, and Device belongsTo user:User.
It is important that only 1 device will never belong to two users so my UserController code looks like this:

class UserController {

static allowedMethods = [create: 'POST']

def index() { }

def create() {
    def user = User.findByUsername(request.JSON?.username)
    def device = Device.findById(request.JSON?.deviceId)
    if (device) {
        device.user.devices.remove(device)
    }
    // device can only be owned by 1 person
    def new_device = new Device(id: request.JSON?.deviceId, type: request.JSON?.deviceType)

    if ( !user ) {
        user = new User(
                username: request.JSON?.username
        )
        user.devices = new HashSet() // without this I get null on the add in next line
        user.devices.add(new_device)
        user.save()

        if(user.hasErrors()){
            println user.errors
        }
        render "user.create " + request.JSON?.username + " devices.size " + user.devices.size()
    } else {
        user.devices.add( new_device )
        user.save()
        if(user.hasErrors()){
            println user.errors
        }

        render "user.create exists, new token: " + user.token + " devices.size " + user.devices.size()
    }
}

}  

But now I get a strange server error:
null id in Device entry (don't flush the Session after an exception occurs)

What am I missing here??

Thanks a lot!

Upvotes: 3

Views: 4614

Answers (1)

Grzegorz Gajos
Grzegorz Gajos

Reputation: 2363

First of all, there are special methods to add to and remove from. Do not operate straight on hasMany collections. Maybe this is problematic.

Upvotes: 8

Related Questions