自定义错误消息无法在带有grails的gorm中工作

时间:2014-08-31 18:29:17

标签: grails gorm

似乎无法获得适用于Grails 2.3.7的自定义验证消息。

class Team {
   int id
   String email

   static mapping = {
     id     column:'TEAM_ID', generator:'native'
     email  column:'TEAM_EMAIL' 
   }
   static constraints = { 
     email  unique:true
   }

messages.properties (尝试了所有这些......)

team.email.unique=Email already used!
Team.email.unique=Email already used!
my.package.Team.email.unique=Email already used!

我的服务选择了验证问题,但从不使用自定义错误消息:

Team t = new Team(...)
if(!t.validate())
   println t.errors

...输出

Field error in object 'Team' on field 'email': rejected value.... ...
default message [Property [{0}] of class [{1}] with value [{2}] must be unique]

不确定问题是什么,根据docs惯例是:

[Class Name].[Property Name].[Constraint Code]

额外配置

BuildConfig

dependencies {
    compile('com.oracle:ojdbc6:11.2.0')
}
plugins {
    build ":tomcat:7.0.52.1"
    runtime ":hibernate:3.6.10.9"
}

数据源

 dialect  =  "org.hibernate.dialect.Oracle10gDialect"
 hibernate {
    cache.use_second_level_cache = false
    cache.use_query_cache = false
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
    singleSession = false 
}

1 个答案:

答案 0 :(得分:2)

className.propertyName.unique根据http://grails.org/doc/2.3.7/ref/Constraints/unique.html的唯一约束文档页面,但println t.errors将始终看起来像您所看到的那样toString()结果并不是非常有用。要查看已解决/已翻译的消息,您可以测试您在测试或测试应用中执行的操作,并可以使用此消息显示已解决的消息:

// dependency injection in controller/service/etc.
def messageSource

...

Locale locale = Locale.getDefault()
def stringsByField = [:].withDefault { [] }

for (fieldErrors in t.errors) {
   for (error in fieldErrors.allErrors) {
      String message = messageSource.getMessage(error, locale)
      stringsByField[error.field] << message
   }
}

println stringsByField