我在 Rails 3.2.3 应用程序中设置了一个嵌套表单,它工作正常,我的模型是:
class Recipe < ActiveRecord::Base
attr_accessible :title, :description, :excerpt, :date, :ingredient_lines_attributes
has_and_belongs_to_many :ingredient_lines
accepts_nested_attributes_for :ingredient_lines
end
and:
class IngredientLine < ActiveRecord::Base
attr_accessible :ingredient_id, :measurement_unit_id, :quantity
has_and_belongs_to_many :recipes
belongs_to :measurement_unit
belongs_to :ingredient
end
如上所述,一个 Recipe 可以有多个 IngredientLine,反之亦然。
我试图避免 IngredienLine 表上的记录重复。
例如,假设对于 Recipe_1,与 {"measurement_unit_id" => 1, "ingredient_id" => 1, "quantity" => 3.5} 关联的 IngredientLine,如果对于 Recipe_5,IngredientLine 子表单由用户使用相同的值进行编译,我不想在 IngredientLine 表中添加新记录,而只希望在连接表成分_lines_recipes 中添加新关联记录。
请注意,目前我没有任何 IngredientLine 控制器,因为保存和更新 IngredientLine 是由嵌套表单例程处理的。甚至我的食谱控制器也是简单而标准的:
class RecipesController < ApplicationController
respond_to :html
def new
@recipe = Recipe.new
end
def create
@recipe = Recipe.new(params[:recipe])
flash[:notice] = 'Recipe saved.' if @recipe.save
respond_with(@recipe)
end
def destroy
@recipe = Recipe.find(params[:id])
@recipe.destroy
respond_with(:recipes)
end
def edit
respond_with(@recipe = Recipe.find(params[:id]))
end
def update
@recipe = Recipe.find(params[:id])
flash[:notice] = 'Recipe updated.' if @recipe.update_attributes(params[:recipe])
respond_with(@recipe)
end
end
我的猜测是这应该足以覆盖标准create
IngredientLine 的行为find_or_create
,但我不知道如何实现它。
但是还有另一个需要注意的重要点,想象一下编辑存在一些 IngredientLine 的子表单,如果我添加另一个已经存储在 IngredientLine 表中的 IngredientLine,rails 当然不应该在 IngredientLine 表上写入任何内容,但也应该区分已经与父级关联的子记录和需要创建关系的新子记录,在连接表上写入新记录。
Thanks!