2012-08-29 21 views
0

得到一個域的特定實例我有一個要求這樣的方法一個GSP文件:Grails中

<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] 
    } 

回答

1

變量在控制器方法(操作)具有本地範圍,因此,僅可以在該方法中使用。你應該從新實例傳遞id並使用該id來檢索對象。

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

和索引可能是

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

然後你就可以斷定你不需要callChildProfile方法

,或者您可以使用PARAMS

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

但這是否意味着每次我打電話索引我都要給它一個長ID? – Sagarmichael

+0

我在答案中寫了一個選擇 –

2

默認控制器是原型範圍,這意味着ProfileController實例將使用不同的賭注請求調用callChildProfile的請求以及調用index的請求。因此,請求之間的對象級別childInstance變量將不可用。

要在index呼叫使用Child實例,看看chain方法:

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

def index() { 
    // do other stuff 
    [otherModelVar:"Some string"] 
} 

當返回Mapindex鏈調用的模型將被自動添加,所以你childInstancecallChildProfile將可用於gsp。