【问题标题】:Grails databinding: creating instances of an abstract classGrails 数据绑定:创建抽象类的实例
【发布时间】:2013-07-05 15:25:07
【问题描述】:

在使用 Grails 时,我喜欢尽可能地依赖自动数据绑定和脚手架。我有以下问题。我有一个域类 Flow,它有一个域类 Node 的实例集合,是最新的一个抽象类:

class Flow {
    List nodes
    static hasMany = [ nodes: Node]
    static constraints = { nodes minSize:1 }
}
abstract class Node {
    String title
    static belongsTo = [ ownerFlow: Flow]
}

有几个类继承自 Node.js。尝试使用数据绑定创建流时,以下集成测试失败:

void "a flow can be created from a single request using the default grails data binding"() {
  when:
    def controller = new FlowController()
    controller.request.addParameters(['nodes[0].title': 'First step'])
    new Flow(controller.params).save(flush:true)
  then:
    Flow.count() > 0
  }
}

当我将 Node 从抽象更改为非抽象时,测试通过了。这是完全有道理的,因为 Grails 无法创建 node[0] 实例,因为 Node 是一个抽象类,但问题是:

  • 有没有办法指定节点的具体类以便创建它?

从技术上讲是完全可能的(事实上,Grails 已经在做类似的事情,通过使用类名列来持久化和检索实例),但我不确定在数据绑定中是否已经考虑过这种情况。如果没有:

  • 您认为不接触控制器的最佳解决方案是什么?

【问题讨论】:

    标签: grails


    【解决方案1】:

    您需要为绑定的目的配置默认值:

    List nodes = [].withDefault { new MyConcreteNode() }
    

    【讨论】:

    • 非常酷,我不知道!问题是我需要一些节点来使用不同的类,但也许我可以尝试使用 params 和 transients 类来解决这个问题......谢谢!
    • 我在 Flow 类中添加了一个名为 nodeClasses 的瞬态属性,在请求参数中为其添加了一些值,以便自动绑定,然后在传递给列表的 withDefault 的闭包中使用它。问题是我猜参数绑定的顺序可能会改变,因为参数是一个地图......有没有办法定义参数绑定的顺序?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多