1

Simplest of models in Grails:

class Author {

    String first_name
    String last_name

    static hasMany = [ books : Book]
    static constraints = {
        first_name()
        last_name()
    }
}

class Book {

    String title
    String subtitle
    Integer pages

    static belongsTo = [author: Author]

    static constraints = {
        title()
        subtitle nullable: true
        pages()

    }
}

In the default scaffolded form created by Grails, Author is included as a form field with the name "author.id". When the save function executes, Grails recognizes author.id as representing something outside the Book object, fetches an instance of Author with the id, and attaches that to the new instance of Book.

In my app, I have taken out the Author field from the new Book form. In the Book controller, I am trying to manually assign the ID of an author (it's saved in a session variable.)

These don't work:

bookInstance.author.id = 1
bookInstance.author = Author.get(1)

When I inspect the bookInstance in the debugger before it gets to the validation, I can see that bookInstance.author is a completely valid object. After the validation fires, bookInstance.author is null.

However,this does work:

def writer = Author.get(1)
writer.addToBooks(bookInstance)

I thought changing from lazy to eager loading on both domain classes might fix it, but it didn't. Can someone explain why this last approach works, but the former approaches do not?

2 Answers 2

0

You need to set up both sides of the relationship. The addToBooks method does (something like) this for you -

bookInstance.author = author
author.books.add(bookInstance)

I think when the grails data binder sees a form parameter like author.id it fetches the author specified by the author.id parameter and sets up each side of the relationship.

0

You shouldn't really be setting the id of a domain class - this field is managed for you by Grails / GORM.

See these posts: here and here

If you want to add an identifier, for example from a controller as you are doing, why not just add it to the domain object as a separate property (called something other than id). You can give it a unique constraint if you wish, which will enforce it being able to be used as a key to look it up, and you'll get to look it up just as quickly if you put an index in the mapping.

class MyClassWithOtherId {
    long myOtherId

    static constraints = {
        myOtherId unique: true
    }

    static mapping = {
        myOtherId index: 'myOtherIndex_idx'
    }
}

Usage:

MyClassWithOtherId.findByMyOtherId(1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.