2012-07-23 76 views
0

我有幾個相關的域類,我試圖找出如何實現一個依賴於多個域的約束。問題的JIST是:Grails驗證依賴於相關域

資產擁有衆多容量池對象

資產擁有衆多的資源對象

當我創建/編輯資源,需要檢查總資源爲一項資產不會超過容量。

我創建了一個完成此操作的服務方法,但是不應該通過資源域中的驗證器完成此操作嗎?我的服務級別如下:

def checkCapacityAllocation(Asset asset, VirtualResource newItem) {  

// Get total Resources allocated from "asset" 
     def allAllocated = Resource.createCriteria().list() { 
      like("asset", asset) 
     } 
     def allocArray = allAllocated.toArray() 
     def allocTotal=0.0 
     for (def i=0; i<allocArray.length; i++) { 
      allocTotal = allocTotal.plus(allocArray[i].resourceAllocated) 
     } 


// Get total capacities for "asset" 
     def allCapacities = AssetCapacity.createCriteria().list() { 
      like("asset", asset) 

     } 
     def capacityArray = allCapacities.toArray() 
     def capacityTotal = 0.0 
     for (def i=0; i<capacityArray.length; i++) { 
      capacityTotal += capacityArray[i].actualAvailableCapacity 
     } 

     if (allocTotal > capacityTotal) { 
      return false 
     } 
    } 
    return true 
} 

我遇到的問題是使用此方法進行驗證。我正在使用JqGrid插件(使用內聯編輯),並且錯誤報告有問題。如果我可以在域中進行這種類型的驗證,它會使事情變得更容易。有什麼建議麼?

非常感謝!

回答

0

要使用該服務方法的驗證,你需要注入的服務爲您的域名,然後添加調用一個自定義的驗證。我認爲它會是這個樣子:

class Asset { 

    def assetService 

    static hasMany = [resources: Resource] 

    static constraints = { 
     resources(validator: { val, obj -> 
      obj.assetService.checkCapacityAllocation(obj, val) 
     }) 
    } 
} 
+0

太棒了!現在我只是得到內聯「行動」格式化與jqgrid正常工作的限制...感謝您的幫助! – Nisrak 2012-07-24 20:49:17

0

如何:

def resourceCount = Resource.countByAsset(assetId) 
def assetCapacityCount = AssetCapacity.countByAsset(assetId) 
if(resourceCount < assetCapacityCount) return true 
return false 

HTH

+0

這使得該方法更短的一個很好的方式,但我仍然不知道如何編輯/添加行的時候使用它作爲一個約束條件進行檢查 – Nisrak 2012-07-24 01:16:18

+0

你可以將我上面寫的代碼添加到@doelleri提到的自定義驗證器中。 – vprasad 2012-07-24 17:19:51