我有以下实体
class Thesis extends Article {
String description
Topic topic
User assignee
User supervisor
...
static constraints = {
supervisor nullable: true
...
supervisor validator: {supervisor ->
if (supervisor?.id != null && !User.get(supervisor.id)) {
'not.found'
}
}
}
}
在没有主管的情况下创建和保存新实例就可以了。
但是,当我尝试从现有论文实例中删除(设置为 null)主管时,我最终会遇到 TransientObjectException。我可能遗漏了一些关于数据绑定的内容,因为如果我不将表单数据绑定到 thesisInstance 并且只是将“supervisor”属性设置为 null,它将毫无问题地保存。
def thesisInstance = Thesis.get(id)
thesisInstance.properties = params.thesis
if (thesisInstance.supervisorId == null){
thesisInstance.supervisor = null
}
thesisInstance.save()
编辑: params.thesis 地图看起来像这样(免责声明:这些是虚拟数据)
thesis.tags.title: ruby
thesis.version: 7
thesis.topic.id: 13
thesis.supervisor.id:
thesis.status: FINISHED
thesis.id: 18
thesis.title: Implementation of Ruby Killing Machine
thesis.type: BACHELOR
thesis.assignee.fullName: Somebody
thesis.university.id: 1
thesis.grade: A
thesis.supervisor.fullName:
thesis.thesisAbstract: Implementation of Ruby Killing Machine that will kill people that are filled in an HTML form.
thesis.description: Implementation of Ruby Killing Machine that will kill people that are filled in an HTML form.
thesis.assignee.id: 4
如您所见,未填充 thesis.supervisor.id,因此将 thesisInstance.supervisor 设置为没有 ID 的新用户实例。因此需要“thesisInstance.supervisor = null”
我在 [1] 上发现了完全相同的问题,但没有得到解答。
[1] http://grails.1312388.n4.nabble.com/Data-Binding-and-Null-ifying-problems-in-G1-2-0-td1339929.html