没有懒惰地初始化一个角色集合

时间:2011-01-27 08:54:24

标签: grails

嘿所有,我正在构建一个m:m db关系的GRAILS应用程序。当我试图显示众所周知的“未能懒惰地初始化角色集合......没有会话或会话被关闭”时,会显示错误。

一个课程是:

class Hazzard{

static hasMany = [warning:Warning]

static constraints = {
    text(size:1..5000)
}

    String name
    String text
    String toxicity
}

另一个:

class Warning{

static hasMany = [hazzard:Hazzard]
static belongsTo = Hazzard

static constraints = {
    text(size:1..5000)
}

    String code
    String text   
}

在Hazzard /中显示以下代码正常

<g:each in="${hazzardInstance.warning}" var="p">
<li><g:link controller="Warning" action="show" id="${p.id}">${p?.encodeAsHTML()}</g:link></li>
</g:each>

但在其他页面上,以下代码将提供错误:

<g:set var="haz" value="${Hazzard.get(params.id)}" />
<h1>${haz.name}</h1>
<p>${haz.text}</p>
<h1>Toxiciteit</h1>
<p>${haz.toxicity}</p>
<br/>
<h1>Gevaren(H) en voorzorgen(P)</h1>
<g:each in="${haz.warning}" var="p"> --> This is where the error pops-up
  ${p.text}
</g:each>

关于失败的地方的任何线索?

1 个答案:

答案 0 :(得分:2)

您尝试做的更有利的方法是在控制器中执行get并将找到的域对象传递给视图进行渲染。类似的东西:

// MyController.groovy
class MyController {
    def myAction = {
        def haz = Hazzard.get(params.id)
        render(view: 'myview', model: [hazzardInstance: haz])
    }
}

// my/myview.gsp (the view from your second GSP code block)
<h1>${hazzardInstance?.name.encodeAsHTML()}</h1>
...
<h1>Gevaren(H) en voorzorgen(P)</h1>
<g:each in="${hazzardInstance?.warning}" var="p">...</g:each>

在视图中进行GORM查找有时会导致您获得的异常,尽管我认为许多类似的问题已在更新版本的Grails中得到修复。尽管如此,使用更正确的习惯用于查询和渲染视图将帮助您避免此错误。