【问题标题】:Grails Domain With "First" and "Last" Properties具有“First”和“Last”属性的 Grails 域
【发布时间】:2013-11-13 17:49:21
【问题描述】:

我最近继承了一个 Grails 代码库,其中包含一个名为 Name 的域类(以及其他),属性 firstlast 分别表示名称的开头和结尾部分。在编写使用该域的单元测试时,我遇到了一些问题,这些问题源于这些属性的名称与 Grails 中的 firstlast 方法相同。现在,我可以通过重命名属性来解决问题,但我想知道 Grails 中是否可以使用属性名称 firstlast

也就是说,当 Grails 尝试将 nullable: true 约束应用于属性时,我收到的错误是 No signature of method: com.example.Name.first() is applicable for argument types: () values: [] Possible solutions: first(), first(java.lang.String), first(java.util.Map), list(), list(java.util.Map), print(java.lang.Object)

这里是Name的来源:

class Name {
    String first
    String middle
    String last
    static belongsTo = [person : Person]

    static constraints = {
        first(nullable:true)
        middle(nullable:true)
        last(nullable:true)
    }

    public static Name findOrCreate(String first, String middle, String last){
        def name
        name = Name.createCriteria().get{
            and{
                eq('first', first)
                eq('middle', middle)
                eq('last', last)
            }
        if(!name){
            name = new Name()
            name.first = first
            name.middle = middle
            name.last = last
        }       
        return name
    }

    static mapping = {
        cache true
    }

}

【问题讨论】:

  • 您应该使用name.first 来获取Name 实例的名字。为什么它会以任何方式与Name.first() 发生冲突?
  • 在约束块中,当 Grails 尝试应用 first(nullable:true) 时,会抛出上述异常。
  • 您的 findOrCreate 方法在功能上与 GORM 添加到所有域类 grails.org/doc/latest/ref/Domain%20Classes/… 的此方法相同

标签: grails


【解决方案1】:

你说这个错误发生在约束块中。在这种情况下,您可以使用显式的delegate. 使其工作,即

static constraints = {
  delegate.first(nullable:true)
  // and similarly for last
}

强制将 first 视为对约束 DSL 的调用,而不是对静态 GORM 方法的调用。

【讨论】:

  • @RandomMooCow 这是一个有用的技巧,可以随时注意与 DSL 的名称冲突。如果我想创建一个与局部变量同名的元素,我经常在使用 MarkupBuilder 编写 XML 时使用它。
猜你喜欢
  • 1970-01-01
  • 2012-05-22
  • 2014-08-21
  • 1970-01-01
  • 2011-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
相关资源
最近更新 更多