【问题标题】:Rails - How to make an association on create for self referenced model?Rails - 如何为自引用模型创建关联?
【发布时间】: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


    【解决方案1】:

    这是一个非常常见的误解,即您需要嵌套属性来进行(现有记录的)简单分配,而事实并非如此。你只需要白名单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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      相关资源
      最近更新 更多