Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 strong params with an Array within check boxes values

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 catch category_ids params {"2"=>"1", "3"=>"1", "4"=>"1"} with the correct permit and require syntax:

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

like image 928
Albert Català Avatar asked Feb 06 '23 13:02

Albert Català


1 Answers

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: [])
like image 181
oreoluwa Avatar answered Mar 24 '23 23:03

oreoluwa