grailsgrails-2.0grails-domain-class

Make field unique based on a boolean field value with multiple column in grails domain


I am using grails-2.5.2 version. I have a field which I want to make unique based on two field. But if the isActive field value is true then it will have one row with the same roll. But if false then multiple entry can be saved with the same roll. My class is below:

    class Student {

    Integer roll
    String name
    Boolean isActive

    static constraints = {
      name(unique: ['roll', 'isActive'])
    }
}

Actually I want the unique like this - name(unique: ['roll', 'isActive' == true])


Solution

  • Actually I want the unique like this - name(unique: ['roll', 'isActive' == true])

    We don't have any specific support in GORM to express something like that. You will need to express that restriction in your own code in the app.

    I am not 100% sure and it may depend on what databases you have to support but I don't think there is going to be a good way to express that kind of restriction in your database either.