The dig method does not work correctly with ActionController::Parameters

Viewed 2130

Documentation: https://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-dig

I run rails c and write this:

params = ActionController::Parameters.new(foo: { bar: { baz: 1 } })

And further:

params.dig(:foo, :bar, :baz)

These two lines I took from the page, the link to which is given above.

As a result, I get nil.

When working with Hash everything is fine. There is a problem when working with ActionController::Parameters. I have this problem inside the Rails application.

Need your opinion on this.

1 Answers

ActionController::Parameters is a subclass of Hash, you can convert it directly to a hash using the to_h method on the params hash.

However to_h only will work with whitelisted params, so you can do something like:

params = ActionController::Parameters.new(foo: { bar: { baz: 1 } })
params.permit!
params.to_h.dig(:foo, :bar, :baz)

But if instead you do not want to whitelist then you just need to use the to_unsafe_h method.

Related