Processing of Requests
Explore how Rails processes incoming web requests by routing them to controller actions using Action Dispatch and Action Controller. Understand how controllers manage request data, sessions, responses, and rendering templates or sending files. This lesson provides a comprehensive view of handling requests and generating appropriate HTTP responses in Rails applications.
We'll cover the following...
In the previous lesson, we worked out how Action Dispatch routes an incoming request to the appropriate code in your application. Now let’s see what happens inside that code.
Action methods
When a controller object processes a request, it looks for a public instance method with the same name as the incoming action. If it finds one, that method is invoked. If it doesn’t find one and the controller implements method_missing(), that method is called, passing in the action name as the first parameter and an empty argument list as the second. If no method can be called, the controller looks for a template named after the current controller and action. If found, this template is rendered directly. If none of these things happens, an AbstractController::ActionNotFound error is generated.
Controller environment
The controller sets up the environment for actions (and, by extension, for the views that they invoke). Many of these methods provide direct access to the information contained in the URL or request:
-
action_nameThe name of the action currently being processed.
-
cookiesThe cookies are associated with the request. Setting values into this object stores cookies on the browser when the response is sent. Rails support for sessions is based on cookies.
-
headersA hash of HTTP headers will be used in the response. By default,
Cache-Controlis set tono-cache. We might want to setContent-Typeheaders for special-purpose applications. Note that we shouldn’t set cookie values in the header directly. Use the cookie API to do this. -
paramsA hash-like object containing request parameters along with pseudo parameters generated during routing. It’s hash-like because we can index entries using either a symbol or a string. The
params[:id]andparams['id']return the same value. Idiomatic Rails applications use the symbol form. -
requestThe incoming request object. It includes these attributes:
-
The
request_methodattribute returns the request method, one of:delete,:get,:head,:post, or:put. -
The
methodattribute returns the same value asrequest_methodexcept for:head, which it returns as:get...
-