Grails数据绑定:创建抽象类的实例 [英] Grails databinding: creating instances of an abstract class

查看:74
本文介绍了Grails数据绑定:创建抽象类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  class Flow {
列表节点
static hasMany = [nodes:Node]
static constraints = {nodes minSize:1}
}
抽象类节点{
字符串标题
static belongsTo = [ownerFlow:Flow]
}

是几个从Node继承的类。当尝试使用数据绑定创建Flow时,以下集成测试失败:

  void可以使用单个请求创建流默认的grails数据绑定(){
when:
def controller = new FlowController()
controller.request.addParameters(['nodes [0] .title':'First step' ])
new Flow(controller.params).save(flush:true)
then:
Flow.count()> 0


抽象的,测试通过。因为Grails不能创建节点[0]实例,因为Node是一个抽象类,但问题是:


  • 是否有一种方法可以指定节点的具体类,以便创建它?



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


  • 您认为没有触摸控制器的最佳解决方案是什么?


解决方案

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

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


When working with Grails, I like to rely on automatic databinding and scaffolding as much as possible. I have the following problem. I have a domain class Flow that have a collection of instances of the domain class Node, being the latest one an abstract class:

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

There are several classes that inherit from Node. When trying to create a Flow using databinding the following integration test fails:

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
  }
}

The moment I change Node from abstract to non-abstract, the test passes. It makes total sense because Grails is not capable of create the node[0] instance, since Node is an abstract class, but the questions is:

  • is there a way to specify the concrete class of the node so it can be created?

Technically is perfectly possible (in fact Grails is already doing something similar for persisting and retrieving the instances by using a classname column), but I'm not sure if this case is already considered in the databinding. If not:

  • what would you think is the best solution without touching the controller?

解决方案

You need to configure a default for the purposes of binding:

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

这篇关于Grails数据绑定:创建抽象类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆