我很难在Grails中自动绑定一对多关系,而无需在控制器中使用一些hack。我明白,Grails中的一对多关系是一个无序的集合,它以某种方式影响绑定。自动绑定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"
}
我怎样组织我的模型和视图这样我就可以离开控制器相对不变?
感谢您的评论,它帮助我找到了正确的解决方案。 – arcdegree