我有一個 self_referenced 模型(類別):
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 關聯以相同的形式創建一個類別模型。
例如數字 => 類別和 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
uj5u.com熱心網友回復:
這是一個非常常見的誤解,即您需要嵌套屬性來進行簡單的分配(現有記錄的),但事實并非如此。您只需要白名單category[sub_theme_ids][]:
def category_params
params.require(:category).permit(
:name,
sub_theme_ids: []
)
end
accepts_nested_attributes_for僅當您想以相同的形式創建類別及其子主題時才需要。在這種情況下,您需要使用fields_for(由簡單的形式包裝為simple_fields_for):
<%= 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 } %>
<fieldset>
<legend>Subthemes</legend>
<%= f.simple_fields_for(:sub_themes) do |st| %>
<%= st.input :name %>
<% end %>
</fieldset>
<%= f.submit "Enregister" %>
<% end %>
def category_params
params.require(:category).permit(
:name,
sub_theme_ids: [],
sub_theme_attributes: [ :name ]
)
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358383.html
