Reputation: 501
I have two domain classes CGroup and Directory, I would like to model a CGroup which has many Directories, however one of these many directories is known as the "root", and is directly accessible from the CGroup. Any CGroup should only ever have one root., and cascades should still work such that the deletion of any directory deletes all of its children.
Although wrong, this is what i have so far:
class CGroup{
...
Directory root
static hasMany = [directory:Directory]
static constraints = {
root(unique:true)
}
}
class Directory {
static hasMany = [children:Directory]
...
static belongsTo = [parent:Directory,
cgroup:CGroup]
static constraints = {
parent nullable: true
}
}
basically, i just need a reference to one instance from the "many" collection, stored in the "one" side
Upvotes: 0
Views: 59
Reputation: 75671
I tried this a few different ways and the only way I could get it working was to allow root
to be temporarily nullable. The problem I had without this was due to ordering - since Directory
instances are in the hasMany
they can't be saved until the CGroup
is saved or the save() call will fail because cgroup
is null (this is set when calling addToDirectory
). But you can't save the CGroup without setting its root
property if it's not nullable.
So I made root
nullable but added a custom validator that fails validation if root
is null and there are any instances in the hasMany
:
static constraints = {
root nullable: true, validator: { Directory root, CGroup cgroup ->
if (!root && cgroup.directory?.size()) {
return ['root.required']
}
}
}
So you would save the CGroup
instance with any required values and without any associated Directory
instances. Then attach the Directory
instances with addToDirectory
and set the root
instance with the custom setter:
void setRoot(Directory root) {
if (this.root) {
removeFromDirectory this.root
}
if (root) {
addToDirectory root
}
this.root = root
}
and save it again:
def group = new CGroup(...).save()
group.root = new Directory(...)
group.addToDirectory(new Directory(...))
group.addToDirectory(new Directory(...))
group.save()
g1.errors
Upvotes: 1