How can I export a user constraint in Grails?

I would like my private constraint check constraints to be outside the scope of the constraint definition for my attribute, because it makes reading and reuse easier, but I'm doing something wrong. I am trying to do this:

class City {
    String name

    static constraints = {
        name( nullable:false, blank:false, validator: uniqueCityValidator )
    }

    def uniqueCityValidator = {
        if ( City.findByNameILike(it) ) return ['cityExists']
    }
}

But I get the following error:

groovy.lang.MissingPropertyException: No such property: uniqueCityValidator for class: com.xxx.City
at com.withfriends.City$__clinit__closure2.doCall(City.groovy:7)
at com.withfriends.City$__clinit__closure2.doCall(City.groovy)
at grails.test.MockUtils.addValidateMethod(MockUtils.groovy:857)
at grails.test.MockUtils.prepareForConstraintsTests(MockUtils.groovy:544)
at grails.test.MockUtils$prepareForConstraintsTests.call(Unknown Source)
at grails.test.GrailsUnitTestCase.mockForConstraintsTests(GrailsUnitTestCase.groovy:116)
at com.xxx.CityTests.testUniqueConstraintForSameCase(CityTests.groovy:9)
+3
source share
1 answer

Closing should be static:

static uniqueCityValidator = {
    if ( City.findByNameILike(it) ) return ['cityExists']
}

We have something similar. In our project, we have our own limitations in our own class. Therefore, we can use them in each class of the domain. The code looks like this:

class Validation {
    static uniqueCityValidator = {
        if ( City.findByNameILike(it) ) return ['cityExists']
    }
}

In the domain class:

static constraints = {
    name( nullable:false, blank:false, validator: Validation.uniqueCityValidator )
}
+6
source

Source: https://habr.com/ru/post/1758326/


All Articles