I’ve got a ClientAttribute domain class, with 2 fields: name (String) & project (Project).
There is a one-to-many relation between Project and ClientAttribute Inside single project, all names have to be unique.
At first I thought about creating following validator:
name(blank: false, validator: { val, obj ->
if (ClientAttribute.findByProjectAndName(obj.project, val)) return ['clientAttribute.name.unique']
})
Unfortunately, when creating new instance of ClientAttribute I do it by adding new instance to the clientAttributes field on project instance and by saving the project instance. This in turn saves rest of the objects in the set clientAttributes. When saving second object in the set, the validator is fired, and it throws me an error, because the findBy() method returns the same object.
I’m wondering, what’s the proper way to perform such check?
I could modify the query not to return the same object as I am currently saving, but I’m wondering if there’s no simpler solution to my problem?
Thanks
Maybe I don’t understand your domain model, but what prevents you from using Grails Unique Constraint in ClientAttribute on both project and name? Like this: