3

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!

John Giotta
  • 16,432
  • 7
  • 52
  • 82
Nadav
  • 1,167
  • 2
  • 19
  • 43
  • what's the value of request.JSON?.deviceId ? Try printing it with log.info(request.JSON?.deviceId) – Paul Feb 10 '12 at 19:38

1 Answers1

8

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

Grzegorz Gajos
  • 2,253
  • 19
  • 26
  • That was indeed the problem. as I said - noob, wasn't aware of these methods. Thank you! – Nadav Feb 10 '12 at 23:31