在使用 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/