嵌套关联 has_many;通过不更新 collection_check_boxes

Nested association has_many;through doesn't update collection_check_boxes

使用复选框更新嵌套表单我无法更新表格。我收到以下消息:

Unpermitted parameter: :category
ActionController::Parameters {"name"=>"Flux Capacitor", "price"=>"19.55"} permitted: true

我尝试了不同的方法通过允许的参数来解决这个问题,包括 :category 参数,如下所示:

def product_params
  params.require(:product).permit(:id, :name, :price, :category, categories_attributes: [:id, :name, :category], categorizations_attributes: [:id, :product_id, :category_ids, :category])
end

我的模型

class Product < ApplicationRecord
  has_many :categorizations
  has_many :categories, through: :categorizations
  accepts_nested_attributes_for :categories, reject_if: proc {|attributes| attributes['name'].blank?}
  accepts_nested_attributes_for :categorizations
end
class Categorization < ApplicationRecord
  belongs_to :product, inverse_of: :categorizations
  belongs_to :category, inverse_of: :categorizations
end
class Category < ApplicationRecord
  has_many :categorizations
  has_many :products, through: :categorizations, inverse_of: :category
end
class ProductsController < ApplicationController

  def edit
    @categories = Category.all
  end

  def new
   @product = Product.new
  end

  def create
    @product = Product.new(product_params)
    if @product.save
      flash[:notice] = 'Product succesfully created'
      redirect_to products_path
    else
      flash[:notice] = 'Product was not created'
      render 'edit'
    end
  end

  def update
    if @product.update(product_params)
      flash[:notice] = "Product succesfully updated"
      redirect_to products_path
    else
      flash[:notice] = 'Product was not updated'
      render 'edit'
    end
  end

app/view/products/edit.html.erb

<%= simple_form_for(@product) do |f| %>
  <%= f.input :name %>
  <%= f.input :price %>
  <%= f.simple_fields_for @product.categories do |cats| %>
    <%= cats.collection_check_boxes  :ids, Category.all, :id, :name, collection_wrapper_tag: :ul, item_wrapper_tag: :li %>
  <% end %>
  <%= f.button :submit %>
<% end %>

这看起来很常见,rails and/or simple_form 应该提供一种更内置的方式来做到这一点。我是否遗漏了一些明显的东西?

如果我对你的理解是正确的,你应该能够在不使用 accepts_nested_attributes_for 或 simple_fields_for 的情况下做到这一点。尝试这样的事情:

<%= simple_form_for(@product) do |f| %>
  <%= f.input :name %>
  <%= f.input :price %>
  <%= f.association :categories, as: :check_boxes %>
  <%= f.button :submit %>
<% end %>

您的强参数应如下所示:

def product_params
  params.require(:product).permit(:id, :name, :price, { category_ids: [] }])
end