自动绑定Grails一对多关系 [英] Auto Binding a Grails One-To-Many Relationship

查看:128
本文介绍了自动绑定Grails一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法自动绑定Grails中的一对多关系,而无需在控制器中使用一些黑客。我明白Grails中的一对多的关系是一个无序的,不知何故的约束。

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.

当我保存此表单时,有时数据可以正确保存,有时候它不是。如果作者有3-4本书,似乎效果较差。

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.

模型:

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

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

查看:

<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>

控制器:

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 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 ]
}

然后视图C一个保持不变,一切都应该按预期工作。

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

这篇关于自动绑定Grails一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆