Rails 5强参数,在复选框值内有一个数组

考虑到这些参数:

"product"=>"", "category_ids"=>"1", "3"=>"1", "4"=>"1"} , "name"=>"...", "description"=>"a good prod", "size"=>"2x3m", "price"=>"23$", "url_video"=>"http://...", "remarks"=>"bla"} 

我想要使​​用正确的permit来进行cath category_ids params {“2”=>“1”,“3”=>“1”,“4”=>“1”}并且require sintax,而不是我不知道:

执行时

 params.require(:product).permit(:name, :size,..., category_ids: [] ) 

结果是

 Unpermitted parameters: id, category_ids 

我试过了params.require(:product).permit(:category_ids[:id,:val]) …和其他变种

什么是正确的sintax?

PD:这些参数是例如:

   

对于has_and_belongs_to_many关系

 class Product < ActiveRecord::Base has_many :images, dependent: :destroy has_and_belongs_to_many :categories, autosave: true attr_accessor :category_list end class Category < ActiveRecord::Base has_and_belongs_to_many :products before_destroy :check_products end 

非常感谢!


经过更多调查,我发现了这篇文章:

在Rails 3.x,4.x和5中有很多通过复选框

解释了这个问题的优点,并且针对Rails 5,进一步解释了如何attr_accessor

我不完全确定,但我认为您应该将复选框更改为如下所示:

   

然后在你的controller#product_params

 params.require(:product).permit(:id, category_ids: []) 

基本上没有允许哈希的语法。 我通常杜有这样的方法ApplicationController

 def nested_params_keys(key, nested_key) (params[key].try(:fetch, nested_key, {}) || {}).keys end 

然后在其他控制器中我允许了参数

 params.require(:product).permit( :name, category_ids: nested_params_keys(:product, :category_ids) )