【发布时间】:2016-12-27 05:41:46
【问题描述】:
我有两个域类 Author 和 Book 相关为一对多。当我为特定作者创建一本新书时,我想(在单击保存按钮后)重定向到作者控制器的显示操作,以便显示特定作者的完整详细信息以及他创作的所有书籍的列表。
class Author {
String fistName
String secondName
static hasMany = [books: Book]
}
class Book {
String title
String dateOfPublication
//Author author
static belongsTo = [author: Author]
}
//BookController
def save() {
def bookInstance = new Book(params)
if (!bookInstance.save(flush: true)) {
render(view: "create", model: [bookInstance: bookInstance])
return
}
flash.message = message(code: 'default.created.message', args: [
message(code: 'book.label', default: 'Book'),
bookInstance.id])
if(params.tempid){
redirect(action: "show", controller: "author", id: params.id)
}else{
redirect(action: "show", id: params.tempid)
}
}
但是,上面的代码并没有按照我的意愿重定向我,而是执行了 else 语句,并显示了 flash 消息“未找到 ID 为 null 的书”
下面是在 Author 类的 show.gsp 中渲染的 _book.gsp 模板。
<table class="table table-striped table-hover" id="book-data">
<thead>
<th class="sortable">Title</th>
<th class="sortable">Date of Publication</th>
</thead>
<tbody>
<g:each in="${authorInstance.book}" status="i" var="p">
<tr class="prop">
<td style="vertical-align: middle;" valign="top" class="value">${p?.title}</td>
<td style="vertical-align: middle;" valign="top" class="value">${p?.dateOfPublication}</td>
<td style="vertical-align: middle;" valign="top"><g:link class="btn btn-edit" action="edit" controller="book" id="${p?.id}"> Edit</g:link></td>
</tr>
</g:each>
</tbody>
</table>
我怎样才能做到这一点。?
感谢您的帮助。
已编辑:authorInstance.id 更改为 params.id
【问题讨论】:
-
您在重定向中使用了
id: authorInstance.id,但您的代码中没有定义authorInstance。 -
我将 authorInstance.id 更改为 params.id 我认为这应该可以工作,但它仍然会产生这条 flash 消息“找不到 ID 为 null 的书”,这是 else 语句的结果。如何访问正确的作者实例?
-
if(params.tempid){ redirect(action: "show", controller: "author", id: params.id) }else{ redirect(action: "show", id: params.tempid) }- 这对我来说看起来很奇怪。如果 tempid 为 null 或为空,您是否使用此值进行重定向?你对这里有什么期望?什么是脾气暴躁?
标签: grails