are a convenient way to pass data from a request to a controller action.
Every request made to a controller action with parameters should be handled with utmost caution.
ActionController::Parameters is a convenient way to do that.
With Rails 7, we can now convert an
object to a standard Hash using the
This is great news for developers who want to customize
the way their data is passed to the controller.
This also means we can change the behavior of the parameters
without having to change anything on the client code.
Let’s assume we have scaffolded a Product model with
product_image as attributes.
Now, if the frontend app sends an appropriate request with appropriate parameters, we should be able to create a new product.
But, what if the client’s request body has different key/value pairs?
Before Rails 7, the way to solve this would be to change strong params keys and then modify the keys one by one inside the controller.
There are a lot of manual updates that are needed in this case which does not feel like a good practice.
Instead, with Rails 7, we can use the
to_h method on the parameters object
to convert it to a standard Hash and then make changes to the keys inside the controller.
This allows us to handle parameters more intelligently without requiring a lot of manual updates.
to_h method doesn’t change the behavior of the parameters object at all,
so there is no need to modify it in any way.
This solution looks and feels a lot like the Rails way. Clean code with easy to understand logic!
The above example is just one way of using the
.to_h method with ActionController::Parameters,
we can also modify the values of the
params hash to be.
Check out the PR for more details.