How to permit params in Rails 4 where the variable param can be either string or hash?

Viewed 336

How to permit params in Rails where the variable param can be either string or hash?

for eg, how to permit param "abc"?

"abc" => "xz" (case1) 
# or 
"abc" => { "v" : "yz"} (case2)

The param can be in any of above format.

If I use params.permit(:abc, abc: [:v]) (thinking this would permit both) but this only permits hash and abc is set to nil when case1.

2 Answers

How about unifying both variants before you use permit/strong parameters?

if params[:abc].is_a? String
  params[:abc] = {v: params[:abc]}
end

Now you know that if :abc is present it will be a Hash.

This is not a good approach, it's better to always have the same type for a param. You should use different names for both these params.

But if you still want to use one name for both kinds of params than you have two options. Either convert string to hash or hash to string before permitting it or add a check to permit according to the type of the param.

if params[:abc].is_a? String
  params.permit(:abc)
else
  params.permit(abc: [:v])
end
Related