简体   繁体   中英

Auto Binding a Grails One-To-Many Relationship

I'm having difficulty auto-binding a one-to-many relationship in Grails without resorting to some hack in the controller. I understand that a one to many relationship in Grails is a set which is unordered and somehow affects binding.

When I save this form, sometimes the data saves correctly, and sometimes it does not. If an author has 3-4 books, it seems that it works less often.

In this example, I've tried to remove all non-relevant code to illustrate the issue.

Models:

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

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

View:

<g:form method="post" class="form-horizontal">
    <g:hiddenField name="id" value="${authorInstance?.id}" />
    <g:hiddenField name="version" value="${authorInstance?.version}" />
    <g:textField name='name' value='${authorInstance?.name}'/>
    <g:each var="book" in="${authorInstance.books}" status="i">
        <g:hiddenField name='book[${i}].id' value='${book.id}'/>
        <g:textField name='book[${i}].title' value='${book.title}'/>
    </g:each>
    <g:actionSubmit action="update" value="Update" />
</g:form>

Controller:

def update(Long id, Long version) {
    def author = Author.get(id)

    // removed "Not Found" and "Version" validation for this example

    author.properties = params

    if (!author.save(flush: true)) {
        render(view: "edit", model: [author: author])
        return
    }

    flash.message = "Success"
    redirect(action: "list"
}

How can I structure my model and view so I can leave the controller relatively untouched?

I've struggled with similar issues submitting one-to-many forms. I solved it in my app by converting the set to a bag.

So unless you specifically need books to be a set, try this:

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

I found that the easiest thing to do was force "Books" to be a List so it's ordered.

class Author {
    List books <------- Added (by default this one-to-many relationship is a Set)
    String name
    static hasMany = [ books:Book ]
}

Then the view can remain the same and everything should work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM