Home > Net >  Reading Rails params from request object
Reading Rails params from request object

Time:08-27

I'm working on Rails 6 and I'm looking into different ways to read params within a controller. I see the Rails documentation lists params[:param_key] as an example, and this does work. However, I have noticed that request[:param_key] also returns the same value. I had a few questions around this behavior:

  1. Why is the request object able to expose these values when being read directly as a hash key? From what I can tell in the docs for this object (https://api.rubyonrails.org/v7.0.3.1/classes/ActionDispatch/Request.html) I can't find anything that would indicate towards this being a behavior that should work.

  2. Is there a benefit to using "params" or the request object for reading parameters within a controller? From my testing both behave the same way, but I would like to know if there is a best practice.

Thank you.

CodePudding user response:

I'm sure if you dig hard enough into the code, you'll find out the answer to your first question.

Regarding the second question, you will eventually need to use sanitized parameters, or "strong parameters", and this operates on the params object. Notice that it is not a hash, but an instance of ActionController::Parameters. In it's raw form it has a permitted=false property, and you will not be able to save any of the incoming parameters until you have explicitly permitted them.

CodePudding user response:

As far as the first question is concerned, I can see a list of included modules including ActionDispatch::Http::Parameters inside the documentation of Request and this module includes a params method. Second question has been perfectly answered by @Les Nightingill

  • Related