4

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

2
  • could you post your product and category models? Commented Jul 18, 2016 at 17:47
  • Sure! I edit the question Commented Jul 18, 2016 at 19:52

2 Answers 2

10

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: [])
Sign up to request clarification or add additional context in comments.

1 Comment

Yes! you can be sure now, that's the solution, Thanks
-1

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)
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.