Grails 数据绑定(bind) : creating instances of an abstract class

标签 grails

在使用 Grails 时,我喜欢尽可能依赖自动数据绑定(bind)和脚手架。我有以下问题。我有一个域类 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。当尝试使用数据绑定(bind)创建流程时,以下集成测试失败:

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 已经在通过使用类名列来执行类似的操作来保存和检索实例),但我不确定数据绑定(bind)中是否已经考虑了这种情况。如果没有:

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

最佳答案

您需要配置默认值以进行绑定(bind):

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

关于Grails 数据绑定(bind) : creating instances of an abstract class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17464516/

相关文章:

java - Grails - 导入 jsch 结果为 "package com.jcraft.jsch does not exist"

grails - 执行列表插件更新时,Grails 2.4.0.RC1:NullPointer

grails - 在 Grails 域类中设置日期字段的默认值

grails - 如何在 Grails 中创建自定义环境?

grails - NetBeans-11无法设置为使用Grails

grails - JobRepository中检测到的现有事务-带有Grails插件的Spring Batch

hibernate - Grails自定义 validator 错误

Java/Grails - PrettyTime NLP 可以拆分非日期部分吗?

grails - GGTS 下载页面的 404

grails - 如何使Grails子查询作为简单示例?