使用复选框更新嵌套表单,我无法更新表。我收到以下消息:
不允许的参数::category
ActionController :: Parameters 允许使用{“ name” =>“助焊剂电容器”,“ price” =>“ 19.55”}
我尝试了各种方法来通过允许的参数来解决此问题,包括: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和/或simple_form应该以一种更内置的方式提供来执行此操作。我缺少明显的东西吗?
答案 0 :(得分: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