You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails自引用模型创建时如何关联子主题,Unpermitted parameter错误如何解决

问题解决方案

问题根源

  • 强参数配置与表单提交参数不匹配:你使用f.association :sub_themes, multiple: true生成的多选框,提交时会传递category[sub_theme_ids]数组参数,而你当前的强参数只允许了嵌套结构的sub_theme_attributes参数,未放行sub_theme_ids,因此触发未授权参数报错。
  • 配置冗余:你的需求是关联已存在的Category作为子主题,不需要新建子主题实例,因此不需要accepts_nested_attributes_for配置,也不需要在new方法中build子主题实例。

修改步骤

1. 修正控制器代码

修改Admin::CategoriesController如下:

class Admin::CategoriesController < AdminController
  def index
    @categories = Category.all
  end

  def new
    @category = Category.new
    # 移除冗余的build代码,不需要提前创建子主题实例
  end

  def create
    @category = Category.new(category_params)
    if @category.save
      redirect_to admin_categories_path
    else
      render :new
    end
  end

  private

  def category_params
    params.require(:category).permit(
      :name,
      # 直接允许sub_theme_ids数组参数,不需要嵌套结构
      sub_theme_ids: []
    )
  end
end

2. (可选)清理模型冗余代码

如果没有「新建主分类的同时创建全新子主题」的需求,可以去掉Category模型中accepts_nested_attributes_for :sub_themes这行冗余配置。

修改完成后重新提交表单,选中的子主题会自动和新建的主分类完成关联,不会再出现未授权参数报错。


内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 20:45:05