I’ve created 2 domain classes called Asset and Tag. Asset can have many Tags
// Asset.groovy
class Asset {
static hasMany = [tags: Tag]
}
// Tag.groovy
class Tag {
static belongsTo = Asset
String word
}
The tags are entered into a textfield in the View, each separated by commas.
When the Asset form is submitted, the AssetController will use Tag.findOrSaveWhere to either create a new Tag or Asset.addToTag
def tags_list = params?.tags?.split(",")
tags_list.each {
def tag = Tag.findOrSaveWhere(word: it.trim())
assetInstance.addToTags(tag)
}
All that works very well, but I’m trying to essentially remove Tags from an Asset if the user updates and deleted a Tag.
How can I remove Tags on update?
EDIT I’ve gotten a little further with this by taking an old approach of deleting all the tags then attempting to save the Asset instance.
assetInstance.tags.clear()
def tags_list = params?.tags?.split(",")
tags_list.each {
def tag = Tag.findOrSaveWhere(word: it.trim())
assetInstance.addToTags(tag)
}
However, this will throw an exception if the Tags are null. In other words, if I delete all tags, saving fails.
Solved my issue. Clearing the tags in the update action was the right move, but I had to be mindful of the empty tags string from the form.
My end result was the following block in my
AssetController