繁体   English   中英

Grails Domain Validator:两个字段,可以为null,但不能同时为两个

[英]Grails Domain Validator: Two fields, either can be null, but not both

我有一个域,其中有两个字段可以为空,但不能同时为两个。 所以这样的事情

class Character {
    Association association
    String otherAssociation
    static constraints = {
        association (validator: {val, obj->  if (!val && !obj.otherAssociation) return 'league.association.mustbeone'})
        otherAssociation (validator: {val, obj->  if (!val && !obj.association) return 'league.association.mustbeone'})
    }
}

但是当我运行如下测试时,我只会遇到失败

void testCreateWithAssociation() {
   def assoc = new Association(name:'Fake Association').save()
   def assoccha = new Character(association:assoc).save()

   assert assoccha
}
void testCreateWithoutAssociation() {
    def cha = new Character(otherAssociation:'Fake Association').save()
    assert cha
}

我究竟做错了什么?

编辑看起来如果我将我的代码分解成这样的东西:

def assoc = new Association(name:'Fake Association')
assoc.save()

一切正常。 但是现在我想知道为什么我不能在其他测试中将.save()放在同一行中并且它有效。

为了使测试通过,您的字段关联和otherAssociation必须为null。 向两者添加可空约束,如下所示:

static constraints = {
    association nullable: true, validator: {val, obj->  if (!val && !obj.otherAssociation) return 'league.association.mustbeone'}
    otherAssociation nullable: true, validator: {val, obj->  if (!val && !obj.association) return 'league.association.mustbeone'}
}

我尝试了它,它的工作原理

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM