2012-07-23 77 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