Validation grails-继承域类属性的验证

Validation grails-继承域类属性的验证,validation,grails,gorm,Validation,Grails,Gorm,我有一个相当直截了当的用户模型,其中有个人资料和专家,他们是特殊用户: class User { static hasOne = [profile: Profile] } class Profile { String country static constraints = { country nullable: true, blank: true } } class Expert extends User { static constraints = {

我有一个相当直截了当的用户模型,其中有个人资料和专家,他们是特殊用户:

class User { static hasOne = [profile: Profile] }

class Profile {
    String country
    static constraints = { country nullable: true, blank: true }
}

class Expert extends User {
    static constraints = {
        profile validator: { val, obj ->
            if (!val.country) {
                val.errors.rejectValue 'country', 'expert.profile.country.nullable'
            }
        }
    }
}
当我创建一个专家时,设置他们的配置文件属性,然后保存专家,这是应该的。但是,如果用户想要保存他们的配置文件,我就必须根据他们是否是专家来正确验证配置文件属性

这就是我到目前为止所做的:

    Expert expert = Expert.get(profile.user.id)
    if (expert) {
        expert.properties = params
        expert.save()
    } else {
        profile.user.properties = params
        profile.user.save()
    }
此代码执行正确的验证并设置正确的错误消息。然而,有(至少)三个问题:

  • 进行概要文件更新的服务不需要真正了解不同类型的用户
  • 在配置文件上设置错误时,配置文件仍会保存 到DB
  • 在第二次尝试之前,错误代码不会转换为消息 用于更新配置文件
  • 验证继承的域类属性的正确方法是什么?或者,是否有一个更好的模型,我可以使用它来实现不同类型的用户具有特定于角色的验证需求的目标


    编辑:事实证明,这三个问题中只有第一个是真实的。另外两个是由试图查询数据库时保存用户对象的标记库引起的。接受的解决方案(根据用户标志在
    配置文件中验证)解决了这个问题。

    我认为您必须设置配置文件属于用户,并且可以为空。之后,您可以在profile类中创建验证器。也许对你来说,专家类型需要一个新的类,但我不确定这是否是强制性的

    也许我可以在用户类中实现一个方法,以了解一个实体是基于其属性的专家,还是属性本身的专家

    class User { 
        static hasOne = [profile: Profile] 
        boolean expert
    }
    
    class Profile {
        static belongsTo = [user: User]
        String country
        static constraints = { 
            country validator: { val, obj ->
                if (obj.user?.expert && !val.country) {
                    val.errors.rejectValue 'country', 'expert.profile.country.nullable'
                }
            } 
            user nullable: true
        }
    }
    

    我认为您必须设置配置文件属于用户,并且可以为空。之后,您可以在profile类中创建验证器。也许对你来说,专家类型需要一个新的类,但我不确定这是否是强制性的

    也许我可以在用户类中实现一个方法,以了解一个实体是基于其属性的专家,还是属性本身的专家

    class User { 
        static hasOne = [profile: Profile] 
        boolean expert
    }
    
    class Profile {
        static belongsTo = [user: User]
        String country
        static constraints = { 
            country validator: { val, obj ->
                if (obj.user?.expert && !val.country) {
                    val.errors.rejectValue 'country', 'expert.profile.country.nullable'
                }
            } 
            user nullable: true
        }
    }
    

    也许专家是isExpert==true的用户,而不是单独的类?然后,除非isExpert==true(域类限制),否则country可以为空(数据库设置)?专家可能是isExpert==true的用户,而不是单独的类?那么country可以为空(数据库设置),除非isExpert==true(域类限制)?