Grails:如何在没有 selection 的情况下使用脚手架在控制器中处理 multi-select?

Grails: How to handle multi-select in controller with scaffolding while storing with no selection?

我有一个域对象类别,它与域对象属性有很多关系

class Category {
    Collection<Attribute> attributes = []
    static hasMany = [attributes:Attribute]

我使用脚手架生成一个多 select 框(与 this question 中提到的一个非常相似的问题不同):

class CategoryController {
    static scaffold = true
}

这会在视图中呈现为 select 框,如下所示:

<select id="attributes" class="many-to-many" size="5" multiple="multiple" name="attributes">
<option value="1">entry 1</option>
<option value="2">entry 2</option>
</select>

当没有select输入select框中的任何条目时,发送表单时不会提交任何内容。因此,select 不会存储 select 框中的所有条目,而是保留之前存储的所有值。

我尝试将自己的 beforeValidate 方法(见下文,类似于 a reply to the question mentioned above 中描述的解决方案)添加到我的 CategoryController 但由于脚手架,它不会被执行(除非我弄错了还有另一个原因):

def beforeValidate() {
    def categoryInstance = Category .get(params.id)
    if (!categoryInstance ) {
        flash.message = message(code: 'default.not.found.message', args: [message(code: 'categoryInstance.label', default: 'Category'), params.id])
        redirect(action: "list")
        return
    }
    if (!(params?.attributes)) {
        categoryInstance.attributes.clear()
    }
}

我现在不知所措。放弃此控制器的脚手架并使用我自己的 beforeValidate 方法?保留脚手架并在其他地方实施该方法?做点别的吗?

在几个网站上读到 grails 的脚手架只是为了提供一个粗略的轮廓,人们需要填充它以获得更细粒度的行为后,我决定使用前面的脚手架并创建我自己的控制器和视图,然后通过修改他们的更新方法。 对于此问题的未来访问者,以下是创建控制器和视图的方法: https://grails.github.io/grails-doc/latest/ref/Command%20Line/generate-all.html