Processing of Requests
Learn to further process requests after getting a REST request.
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_name
The name of the action currently being processed.
-
cookies
The 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.
-
headers
A hash of HTTP headers will be used in the response. By default,
Cache-Control
is set tono-cache
. We might want to setContent-Type
headers for special-purpose applications. Note that we shouldn’t set cookie values in the header directly. Use the cookie API to do this. -
params
A 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. -
request
The incoming request object. It includes these attributes:
-
The
request_method
attribute returns the request method, one of:delete
,:get
,:head
,:post
, or:put
. -
The
method
attribute returns the same value asrequest_method
except for:head
, which it returns as:get
because these two are functionally equivalent from an application’s point of view. -
The
delete?
,get?
,head?
,post?
, andput?
...
-