我正在从 Controller 中的父域模型更新一对多。
代码如下所示:
def update() {
def parentInstance = Parent.get(params.id)
params.childerenDetails.each {
parentInstance.addToChildrens(
newChildren(
name:params.get(name_"${it}"),
age:params.get(age_"${it}"))
}
}
if(parentInstance.validate()) {
parentInstance.save(flush:true)
} else {
render "error found at"+parentInstance.errors
}
}
....这里我在父类中有自定义验证,当添加子值得到父验证错误但子对象正在保存到数据库中..如果验证错误出现在父域中,如何防止
最佳答案
如果您想防止将 child 存储到数据库中,您需要将此代码移动到 Service
,默认是事务性的,或者将所有代码封装在 Parent.withTransaction { // }
中.如果您选择使用该服务,您可以发送 RuntimeException
当您检测到验证错误以强制回滚时。如果您使用 withTransaction
,您可以使用 status.setRollbackOnly
手动回滚:
def parentInstance = Parent.get(params.id)
Parent.withTransaction { status ->
params.childerenDetails.each {
parentInstance.addToChildrens(
newChildren(
name:params.get(name_"${it}"),
age:params.get(age_"${it}"))
}
}
if(parentInstance.validate()) {
parentInstance.save(flush:true)
} else {
status.setRollbackOnly()
}
}
不确定
parentInstance.save(flush: true, failOnError: true)
也会触发回滚。我更愿意将业务逻辑移至服务。见 withTransaction和 Services引用指南中的文档。
关于Grails 从父域模型更新一对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27457042/