IainK IainK - 9 days ago 5
Ruby Question

Assistance in understanding the following methods: request.query_string

I've tried searching both the site and the Ruby docs, however, I am unable to find a clear answer to exactly what the above is doing.

From what I understand, 'request' and 'query_string' are two separate methods, however I'm really unsure what they do - the latter in particular.

Any help would be super appreciated!

Thank you.

Answer

In Rails, the #request method available in controllers and views returns a ActionDispatch::Request instance. The Request object allows access to data from the HTTP Request.

The #query_string method, defined in Rack::Request::Helpers, returns the query string from the request url. This is the part in the url following the "?" which specifies url encoded data in the format key=value&other_key=other_value.

Note:

ActionDispatch::Request is a Rails class that behaves similarly to a Rack::Request, including Rack::Request::Env and Rack::Request::Helpers in the current version of Rails v 5.0. In previous versions ActionDispatch::Request inherited directly from Rack::Request.

Read more: