在约束中使用来自域 class 的字段

Using field from domain class in constrinsts

如何使用域 class 中的一个字段为 GORM 设置最大值?

class Test {
    Date start
    Date end

    static constraints = {
        end max: new Date()
        start max: end // <-- here is the problem
    }
}

如果我像上面那样做,我会收到错误消息:

No such property: start for class: org.grails.datastore.mapping.config.groovy.MappingConfigurationBuilder
groovy.lang.MissingPropertyException: No such property: start for class: org.grails.datastore.mapping.config.groovy.MappingConfigurationBuilder
...

我正在使用 Grails 3.0.4

我认为要求是将 start 的最大值设置为运行时的 end 日期。这只能通过使用如下自定义验证器来实现:

class Test {
    Date start
    Date end

    static constraints = {
        end max: new Date()
        start validator: { val, obj ->
            // val - The value of the property on which the validator is applied
            // obj - this object
            if( val > obj.end ) {
                // return false
                // or return max error
                // or return ['some message to pick up from message bundle']
            }
        }
    }
}

有关更多详细信息,请参阅 validator