如何对grails上的域字段应用新验证

时间:2016-05-13 14:22:50

标签: grails gorm

我有这个域名:

class Foo {
  static hasMany=[
    bars: Bar
  ]

  String name

  static constraints = {
    name(blank: false, unique: true)
  }
}

在向数据库插入值后,我添加了另一个条形验证

bars(nullable: false, validator: {value, object ->
            if(value.isEmpty()){
               return['bars.empty.validation.error']
            }
        })

现在,当我尝试更新保存时没有条形保存的Foo实例时,会在字段bars上抱怨:

Field error in object 'Foo' on field 'bars': rejected value [[Bar : (unsaved)]]

我的问题是如何更新Foo实例,而不是bars

1 个答案:

答案 0 :(得分:3)

You could change your custom validation to only apply to instances that don't have an id associated with them (indicating they are being inserted and not updated). Such as this:

bars(nullable: false, validator: {value, object ->
  if (object?.id) return // don't apply to previously saved instance.
  if(value.isEmpty()){
    return['bars.empty.validation.error']
  }
})