Rails 6 多同名字段表单对象创建及未许可参数问题解决
问题核心根因
- 未许可参数报错:表单通过
fields_for生成的嵌套字段名是ingredients、recipe_ingredient_relations,但控制器强参数仅允许Rails嵌套表单约定的带_attributes后缀的嵌套字段结构;同时普通文本输入上额外加了multiple: true属性,导致参数结构变成非预期的数组格式,无法匹配强参数规则。 - i_name校验为空报错:食材名称的字段值全部被包裹在嵌套的
ingredients哈希中,没有被映射到Form Object顶层的i_name属性上,校验时读取到的属性值为空,触发空值校验失败。 - 现有Form Object逻辑仅支持单组食材数据的写入,完全没有处理多组输入的参数结构,无法实现批量录入多组食材及关联关系的需求。
分步修正实现
1. 重构Form Object支持多组嵌套数据处理
替换原有仅支持单字段赋值的Form Object逻辑,增加嵌套属性的接收、校验、事务式批量创建能力:
class RecipesIngredient include ActiveModel::Model attr_accessor :name, :image, :portions, :time_count_id, :recipe, :tips, :calories, :is_public, :user_id, :ingredients_attributes, :recipe_ingredient_relations_attributes # 主Recipe字段校验 with_options presence: true do validates :name validates :portions validates :time_count_id, numericality: { other_than: 1 } validates :recipe validates :is_public end validates :tips, :calories, allow_blank: true # 嵌套子数据校验 validate :check_valid_ingredient_group validate :check_relation_quantity_length def save return false unless valid? # 事务包裹所有写入操作,避免出现部分数据残留 ActiveRecord::Base.transaction do @recipe = Recipe.create!( user_id: user_id, name: name, image: image, portions: portions, time_count_id: time_count_id, recipe: recipe, tips: tips, calories: calories, is_public: is_public ) # 逐组匹配食材和对应关联关系写入 ingredients_attributes.each do |index, ingredient_attr| next if ingredient_attr[:i_name].blank? ingredient = Ingredient.create!(i_name: ingredient_attr[:i_name]) relation_attr = recipe_ingredient_relations_attributes[index] RecipeIngredientRelation.create!( recipe_id: @recipe.id, ingredient_id: ingredient.id, quantity: relation_attr[:quantity], measurement_id: relation_attr[:measurement_id] ) end end true rescue ActiveRecord::RecordInvalid false end private def check_valid_ingredient_group has_valid_ingredient = ingredients_attributes&.values&.any? { |attr| attr[:i_name].present? } errors.add(:ingredients, "至少需要录入一组食材") unless has_valid_ingredient end def check_relation_quantity_length recipe_ingredient_relations_attributes&.values&.each do |attr| next if attr[:quantity].blank? errors.add(:quantity, "长度不能超过10") if attr[:quantity].length > 10 end end end
2. 修正控制器强参数与初始化逻辑
匹配Form Object的嵌套字段结构,在new动作中初始化默认的空嵌套字段,让表单首次加载时可以显示第一组输入框:
# app/controllers/recipes_controller.rb class RecipesController < ApplicationController def index @recipe = Recipe.all end def new @recipes_ingredient = RecipesIngredient.new # 初始化第一组默认空字段 @recipes_ingredient.ingredients_attributes = { "0" => { i_name: "" } } @recipes_ingredient.recipe_ingredient_relations_attributes = { "0" => { quantity: "", measurement_id: "" } } end def create @recipes_ingredient = RecipesIngredient.new(recipe_params) if @recipes_ingredient.save redirect_to root_path, notice: "レシピを投稿しました" else render :new end end private def recipe_params params.require(:recipes_ingredient).permit( :name, :image, :portions, :time_count_id, :recipe, :tips, :calories, :is_public, ingredients_attributes: [:i_name], recipe_ingredient_relations_attributes: [:quantity, :measurement_id] ).merge(user_id: current_user.id) end end
3. 修正视图表单的嵌套字段结构
移除普通输入框上多余的multiple: true属性,保证每组食材名称、数量、度量字段使用相同的索引key,生成符合Rails约定的嵌套参数结构:
<%= form_with(model: @recipes_ingredient, url: recipes_path, local: true) do |form| %> <!-- 主表字段区域省略 --> <div class="ingredient-group-container"> <% @recipes_ingredient.ingredients_attributes.each do |index, ingredient| %> <%= form.fields_for :ingredients_attributes, ingredient do |ingredient_form| %> <div class="ingredient-row" data-index="<%= index %>"> <%= ingredient_form.text_field :i_name, placeholder: "例)レタス", class: "form-el ingredient-input required" %> <%= form.fields_for :recipe_ingredient_relations_attributes, @recipes_ingredient.recipe_ingredient_relations_attributes[index] do |relation_form| %> <div class="quantity"> <%= relation_form.text_field :quantity, placeholder: "例)100", class: "form-el quantity-input required" %> <%= relation_form.collection_select(:measurement_id, Measurement.all, :id, :name, {}, { class: "after-input-required" }) %> </div> <% end %> <button type="button" class="remove-ingredient-btn">-</button> </div> <% end %> <% end %> <button type="button" class="add-ingredient-btn">+</button> </div> <!-- 提交按钮区域省略 --> <% end %>
4. 多行输入的JS实现注意事项
- 点击+号新增食材行时,需要生成递增的数字索引,同时为食材名称、数量、度量字段绑定相同的索引值,保证提交的参数结构为一一对应的嵌套哈希:
"ingredients_attributes": { "0": {"i_name": "水"}, "1": {"i_name": "塩"} }, "recipe_ingredient_relations_attributes": { "0": {"quantity": "100", "measurement_id": "3"}, "1": {"quantity": "小さじ1", "measurement_id": "5"} } - 点击-号删除食材行时,直接移除对应DOM元素即可,因为未传入已存在记录的id参数,不需要额外触发destroy标记。
内容的提问来源于stack exchange,提问作者cafelatte.here
相关产品推荐
相关产品推荐

