Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails params.require on empty hash

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?

like image 818
user3809888 Avatar asked Oct 27 '25 21:10

user3809888


1 Answers

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?
like image 51
Sharvy Ahmed Avatar answered Oct 30 '25 11:10

Sharvy Ahmed