grails - 继承域 class 属性的验证
grails - validation of inherited domain class attributes
我有一个相当简单的用户模型,有个人资料和专家,他们是特殊用户:
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()
}
此代码进行了正确的验证并设置了正确的错误消息。但是,存在(至少)三个问题:
- 执行配置文件更新的服务实际上不需要了解不同类型的用户。
- 虽然在配置文件上设置了错误,但配置文件仍被保存
到数据库。
- 直到第二次尝试,错误代码才会变成消息
用于更新配置文件。
验证继承域 class 属性的正确方法是什么?或者,是否有更好的模型可用于实现具有特定角色验证要求的不同类型用户的目标?
编辑: 事实证明,三期中只有第一期是真实的。另外两个是由于在尝试查询数据库时保存用户对象的标记库引起的。已接受的解决方案(Profile
中基于用户标志的验证)解决了这个问题。
我认为您必须将个人资料设置为属于某个用户,并且可以为空。之后,您可以在配置文件 class 中创建验证器。也许对你来说,专家类型需要一个新的 class,但我不确定这是否是强制性的。
也许我可以在用户 class 中实现一种方法,根据实体的属性或 属性 本身
来了解实体是否是专家
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
}
}
我有一个相当简单的用户模型,有个人资料和专家,他们是特殊用户:
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()
}
此代码进行了正确的验证并设置了正确的错误消息。但是,存在(至少)三个问题:
- 执行配置文件更新的服务实际上不需要了解不同类型的用户。
- 虽然在配置文件上设置了错误,但配置文件仍被保存 到数据库。
- 直到第二次尝试,错误代码才会变成消息 用于更新配置文件。
验证继承域 class 属性的正确方法是什么?或者,是否有更好的模型可用于实现具有特定角色验证要求的不同类型用户的目标?
编辑: 事实证明,三期中只有第一期是真实的。另外两个是由于在尝试查询数据库时保存用户对象的标记库引起的。已接受的解决方案(Profile
中基于用户标志的验证)解决了这个问题。
我认为您必须将个人资料设置为属于某个用户,并且可以为空。之后,您可以在配置文件 class 中创建验证器。也许对你来说,专家类型需要一个新的 class,但我不确定这是否是强制性的。
也许我可以在用户 class 中实现一种方法,根据实体的属性或 属性 本身
来了解实体是否是专家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
}
}