Grails验证依赖于相关域

时间:2012-07-23 23:58:06

标签: validation grails groovy jqgrid dependencies

我有几个相关的域类,我试图弄清楚如何实现依赖于多个域的约束。问题的主旨是:

资产有许多容量池对象

资产有许多资源对象

创建/编辑资源时,需要检查资产的总资源是否超过容量。

我创建了一个服务方法来实现这一点,但是不应该通过资源域中的验证器来完成吗?我的服务类如下:

    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插件(带内联编辑)并且错误报告存在问题。如果我可以在域中进行这种类型的验证,它将使事情变得更容易。有什么建议吗?

非常感谢!

2 个答案:

答案 0 :(得分:0)

怎么样:

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

HTH

答案 1 :(得分:0)

要将服务方法用作验证程序,您需要将服务注入您的域,然后添加一个调用它的自定义验证程序。我认为它看起来像这样:

class Asset {

    def assetService

    static hasMany = [resources: Resource]

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