简体   繁体   English

自动绑定Grails一对多关系

[英]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. 我在Grails中自动绑定一对多关系时遇到困难,而不需要在控制器中使用一些hack。 I understand that a one to many relationship in Grails is a set which is unordered and somehow affects binding. 我知道Grails中的一对多关系是一个无序的集合,并以某种方式影响绑定。

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. 如果作者有3-4本书,那么它似乎不那么频繁。

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: 所以除非你特别需要books作为一套,试试这个:

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. 然后视图可以保持不变,一切都应该按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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