【发布时间】:2021-12-24 03:22:39
【问题描述】:
我有一个自引用模型(类别):
class Category < ApplicationRecord
has_many :sub_themes_association, class_name: "SubTheme"
has_many :sub_themes, through: :sub_themes_association, source: :sub_theme
has_many :inverse_sub_themes_association, class_name: "SubTheme", foreign_key: "sub_theme_id"
has_many :inverse_sub_themes, through: :inverse_sub_themes_association, source: :category
accepts_nested_attributes_for :sub_themes
end
我想创建一个与他的 sub_themes 关联形式相同的类别模型。
例如 Digital => 类别和 SEO & Coding => sub_themes
class Admin::CategoriesController < AdminController
def index
@categories = Category.all
end
def new
@category = Category.new
@sub_themes = @category.sub_themes.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_attributes: [
sub_theme_ids:[]
]
)
end
end
还有形式:
<%= simple_form_for [:admin,@category] do |f| %>
<%= f.error_notification %>
<%= f.input :name %>
<%= f.association :sub_themes, as: :select, collection: Category.all, input_html: { multiple: true } %>
<%= f.submit "Enregister" %>
<% end %>
表单已正确显示,但在创建时出现错误且关联未保留。
不允许的参数::sub_theme_ids
【问题讨论】:
标签: ruby-on-rails simple-form self-reference