Grails:将项目添加到列表并将其附加到其父对象

Grails: Add items to list and attach it to its parent object

我有一个 Recipe、Ingredient 和 RecipeIngredient 域,如下所示:

class Ingredient {
    String title
}

class Recipe {

    String title
    String description

    static hasMany = [ingredients: RecipeIngredient]
}

class RecipeIngredient {

    Ingredient ingredient

    static belongsTo = [recipe: Recipe]

    Measure measure
    Double amount
}

在我的 recipe/Create.gsp 页面中,当我想创建一个新食谱时,我想将其成分逐一添加并添加到食谱实例并将它们一起保存。

<g:form controller="recipe" action="save" method="POST">
    **/* HERE I WANT TO BE ABLE TO ADD ALL INGREDIENTS ONE BY ONE */
    <select value="${recipe_ingredient.ingredient}">
        <g:each in="${allIngredients}" status="i" var="ingredient">
            <option>${ingredient.title}</option>
        </g:each>
    </select>
    <select name="recipe_ingredient.measure" value="${recipe_ingredient.measure}">
        <g:each in="${enums.Measure.values()}" var="m">
            <option>${m}</option>
        </g:each>
    </select>
    <input name="recipe_ingredient.amount" placeholder="Measure" value="${recipe_ingredient.amount}" />
    <g:actionSubmit value="Add" action="addIngredient" />
    /* END */**

    <div class="row">
        <input name="title" value="${instance?.title}" placeholder="Title" />
    </div>

    <div class="row">
        <input name="titleEng" value="${instance?.description}" placeholder="Description" />
    </div>

    <div class="row">
        <g:submitButton name="Create" />
    </div>
</g:form>

我怎样才能实现这样的目标?

直接的方法是:

<g:select name="rawIngredients" value="${recipe.ingredients*.ingredient*.id}"
  from="${allIngredients}" optionKey="id" optionValue="title" multiple="true"/>

然后在控制器中:

def save() {
  Recipe recipe // bind or create somehow, e.g. via command-object

  recipe.ingredients?.clear()

  Ingredient.getAll( params.list( 'rawIngredients' ) ).each{ ing ->
    recipe.addToIngredients new RecipeIngredient( ingredient:ing, amount:1, ... )
  }

  recipe.save()
}