Question

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.

Était-ce utile?

La 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()
}

Autres conseils

How about creating a another Domain class BookAuthor which has both book and author instances..

something like Grails form creation for many-to-one belongsTo

and then do

grails generate-all BookAuthor

I think this will help you to create both records.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top