문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top