4

In one of my controllers I have the line:

params.require(:ad).permit(permitted_array)

params[:ad] is a hash. When permitted keys are present in this hash, this line works fine. When params[:ad] is an empty hash, the above line fails.

Example: With params being

{"ad"=>{}, "controller"=>"ads", "action"=>"create"}

I get this error after params.require(:ad) is called:

ActionController::ParameterMissing:
   param is missing or the value is empty: advertiser

But this works fine:

[2] pry()> params
=> {"ad"=>{"name"=>"kjj", "ad_type_id"=>1, "fee"=>"9", "click_attr"=>"8", "imp_attr"=>"7"}, "controller"=>"ads", "action"=>"create"}
[3] pry()> params.require(:ad).permit(permitted_array)
=> {"name"=>"kjj", "ad_type_id"=>1, "fee"=>"9", "click_attr"=>"8", "imp_attr"=>"7"}

How can I get this line to accept an empty hash?

user3809888
  • 377
  • 1
  • 6
  • 23
  • http://stackoverflow.com/questions/17687506/how-to-make-an-optional-strong-parameters-key-yet-still-filter-params-nested-in – lcguida Jan 14 '16 at 21:38

1 Answers1

12

Make the params require conditional, require the key only if it is present, like this:

params.require(:ad).permit(permitted_array) if params[:ad].present?
Sharvy Ahmed
  • 7,247
  • 1
  • 33
  • 46