【问题标题】:getting a particular instance on a domain in grails在 grails 中获取域上的特定实例
【发布时间】:2012-08-29 18:31:59
【问题描述】:

我有一个 gsp 文件,它调用这样的方法:

<g:link id="${child.id}" action="callChildProfile" controller="profile">${child.firstname}</g:link>

调用这个方法

    def callChildProfile(Long id){

           childInstance = Child.get(id)
           System.out.println(childInstance.firstname + "  child instance")
           redirect(action:  "index")

   }

此方法将一个子实例设置为一个称为子实例的公共变量,但是当重定向发生时,该变量会被重置。 我重定向的原因是因为我想从这个控制器加载索引页面。

索引如下所示:

        def index() {
        def messages = currentUserTimeline()
        [profileMessages: messages]
         System.out.println(childInstance + " child here")
        [childInstance : childInstance]
    } 

【问题讨论】:

    标签: grails


    【解决方案1】:

    默认情况下,控制器是原型范围的,这意味着在调用callChildProfile 的请求和调用index 的请求之间,使用的ProfileController 实例将不同。因此,对象级别的childInstance 变量在请求之间将不可用。

    要在index 调用中使用Child 实例,请查看chain 方法:

    callChildProfile(Long id){
        // do usual stuff
        chain(action:"index", model:[childInstance:childInstance])
    }
    
    def index() {
        // do other stuff
        [otherModelVar:"Some string"]
    }
    

    当从 index 返回 Map 时,将自动添加链调用的模型,因此您从 callChildProfile 获得的 childInstance 将可用于 gsp。

    【讨论】:

      【解决方案2】:

      控制器方法(动作)中的变量具有本地范围,因此只能在该方法中使用。您应该从新实例传递 id 并使用该 id 检索对象。

      redirect action: "index", id: childInstance.id
      

      索引可以是

      def index(Long id){
          childInstance = Child.get(id)
      

      那么就可以断定不需要callChildProfile方法了

      或者你可以使用参数

      def index(){
          childInstance = Child.get(params.id)
          if(childInstance){
              doSomething()
          }
          else{
              createOrGetOrDoSomethingElse()
          }
      }
      

      【讨论】:

      • 但这是否意味着每次我调用 index 我都必须给它一个长 ID?
      • 我在回答中写了一个替代方案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      相关资源
      最近更新 更多