Grails数据绑定:创建抽象类的实例 [英] Grails databinding: creating instances of an abstract class
问题描述
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屋!