Search code examples
grailsgrails-orm

Grails -> GORM -> forcing only one


I'm trying to ensure there is only one row record for the following entity:

class CreditType {

String name

String external_id

Boolean usedForWaivedFee = Boolean.FALSE // default to false

static hasMany = [credits: Credit]

  static constraints = {
   external_id unique: true
   name unique: true
  }
}

Or, put another way, I'm trying to ensure there is only one row with "usedForWaivedFee" is true.

The best idea I have is: custom validator in contrainsts which loops through all current CreditType and ensures there isn't any existing.

Thoughts?

Any suggestions?


Solution

  • Instead of looping through all the instances, you can use countBy method in custom validator. For example, you can use following custom validator

    static constraints = {
    
            usedForWaivedFee validator: { val, obj ->
                if (val) {
                    if (CreditType.countByUsedForWaivedFee(Boolean.TRUE)) {
                        return false
                    }
                }
                return true
            }
    }