Search code examples
formsgrailsgrails-ormone-to-many

Grails how to create a form for a one-to-many relationship where the ownee creates the owner


I have two classes: Book and Author; An author can have many books and a book belongs to one author.

I need to create a form for adding a book. When the create button is pressed i want to create the book record AND the author record. Currently, the default scaffold renders a list box to select from the existing authors, so i need this replacing with a text box instead.

Here are simplified versions of my classes:

class Book {
    static belongsTo = [author:Author]
    String title
}

class Author {
    static hasMany = [books:Book]
    String name
}

All of the tutorials I have found online only contain examples of the Author form also creating the books and not the other way around. How would one do this?

Thanks.


Solution

  • You can create a form with 2 text box, one for title of book and one for author of book. I will assume that author's name is unique, the controller's code will be something like:

    def saveBookForm(String title, String name) {
        Author author = Author.findByName(name)
        if (author == null) {
            author = new Author(name:name).save()
        }
        new Book(title:title, author:author).save()
    }