Rails 5 strong params with an Array within check boxes values

我与影子孤独终老i 提交于 2019-12-23 17:33:00

问题


Given these params:

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

I want to cath category_ids params {"2"=>"1", "3"=>"1", "4"=>"1"} with the correct permit and require sintax, than I don't know:

when execute

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

the result is

Unpermitted parameters: id, category_ids

I have tried params.require(:product).permit(:category_ids[:id,:val])... and other variants

what is the correct sintax?

PD: These params are the result of , for example:

<input type="checkbox" name="product[category_ids][2]" id="product_category_ids_2" value="1">
<input type="checkbox" name="product[category_ids][3]" id="product_category_ids_3" value="1">

for a has_and_belongs_to_many relation

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

Thanks a lot!


After more investigations, I found this article:

Has Many Through Checkboxes in Rails 3.x, 4.x and 5

Explains the good maners about this issue, and is for Rails 5, furthermore explains how attr_accessor is not necessary


回答1:


I'm not totally sure, but I think you should change your checkbox to look like this:

<input type="checkbox" name="product[category_ids][]" id="product_category_ids_2" value="2">
<input type="checkbox" name="product[category_ids][]" id="product_category_ids_3" value="3">

Then in your controller#product_params:

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



回答2:


Basically there is no syntax to permit hash. What I usually du is having such method ApplicationController

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

And then in other controllers I have permitted params

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


来源:https://stackoverflow.com/questions/38442592/rails-5-strong-params-with-an-array-within-check-boxes-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!