2013-07-26 25 views
2

我有兩個類父類:的Grails - 更新家長和孩子的物品拋出越界異常

class parentItem{ 
    User  user 

    Date startTime 
    Date endTime 
    ------ 

    Date  dateCreated 
    Date  lastUpdated 

    static hasMany = [ childItems: ChildItem ] 

和子類

class ChildItem{ 


static belongsTo = [parent : ParentItem]  
--------- 
Date time 
Date dateCreated 
Date lastUpdated 

在GSP文件,使項目成爲編輯我有一個表的行看起來像這樣:

<table id="childDataTable" class="childData"> 
<g:each in="${ParentInstance?.childItems?.sort{it.id}}" var="childItem" status="i"> 
<tr class="childRow"> 
      <td> 
     <g:hiddenField name="childItems[${i}].id" value="${childItem.id}"/</td> 
     ------ 
     <td> 
     <g:textField name="childItems[${i}].time" class="time" value="${childItem.time}"/> 

      </td>    
      <td><a href="#" class="removeButton">&#10006;</a></td> 
     </tr> 
    </g:each> 
     </table> 

所以我的問題源於這樣一個事實:在控制器中,我試圖更新這個parentItem,其中一些childItem數據也可能已被更改。我需要parentItem和childItems的集合來更新和保存。

在控制器我已經試過這

def parentInstance = ParentItem.get(params.id) 
bindData(parentInstance, params) 

,我已經試過

def parentInstance = ParentItem.get(params.id 
parentInstance.properties = params 

這兩種方法,我得到一個出界異常

的在我的情況下,兩個孩子項目消息看起來像這樣:

Index: 1, Size: 1. Stacktrace follows: 
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 
at java.util.ArrayList.rangeCheck(ArrayList.java:604) 
at java.util.ArrayList.get(ArrayList.java:382) 
at com.sexingtechnologies.laboratory.ParentItemController$_closure7$$EOChoLzu.doCall(ParentItemController.groovy:158) 
at grails.plugin.multitenant.core.servlet.CurrentTenantServletFilter.doFilter(CurrentTenantServletFilter.java:53) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) 
at java.lang.Thread.run(Thread.java:722) 

我不確定錯誤的存在位置或解決方法。

我試圖從params地圖中提取childItems,但一直未能成功完成。

任何幫助你理解

回答

0

也許你可以初始化數據,像這樣結合前childItems

def parentInstance = ParentItem.get(params.id) 
parentInstance.childItems = [].withDefault { new ChildItem() } 
bindData(parentInstance, params) 

See here for more about the withDefault method

+0

這很好。我擔心它會增加新的記錄並保留原件,但很高興地發現它確實只是更新記錄。非常感謝您的幫助! – user2623044

+0

是的,它最終只訪問它將要更新的那些。 :)它會創建新的,如果你刪除了輸入隱藏的ID,但。很高興它成功了,不客氣。 – elias

+0

我們用這種方法得到的問題是,它不會更新所有傳入的實體。它執行第1個,然後第2個執行兩次,完全跳過第3個。 – cdeszaq