嵌套关联has_many; through不更新collection_check_boxes

问题描述 投票:0回答:1

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

未允许的参数:: category ActionController :: Parameters {“name”=>“Flux Capacitor”,“price”=>“19.55”}允许: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

应用程序/视图/产品/ 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和/或simple_form应该以更加内置的方式提供。我错过了一些明显的东西吗

ruby-on-rails ruby nested simple-form
1个回答
0
投票

如果我正确理解你,你应该能够在不使用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
© www.soinside.com 2019 - 2024. All rights reserved.