我有这个域名:
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
答案 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']
}
})