[英]Auto Binding a Grails One-To-Many Relationship
我在Grails中自动绑定一对多关系时遇到困难,而不需要在控制器中使用一些hack。 我知道Grails中的一对多关系是一个无序的集合,并以某种方式影响绑定。
当我保存此表单时,有时数据会正确保存,有时则不会。 如果作者有3-4本书,那么它似乎不那么频繁。
在这个例子中,我试图删除所有不相关的代码来说明问题。
楷模:
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"
}
如何构建我的模型和视图,以便我可以保持控制器相对不受影响?
我一直在努力解决提交一对多表格的类似问题。 我通过将设备转换为包来解决它在我的应用程序中。
所以除非你特别需要books
作为一套,试试这个:
class Author {
String name
Collection<Book> books
static hasMany = [ books:Book ]
}
我发现最简单的办法就是强制“书籍”成为一个列表,这样才能订购。
class Author {
List books <------- Added (by default this one-to-many relationship is a Set)
String name
static hasMany = [ books:Book ]
}
然后视图可以保持不变,一切都应该按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.