Controllers in Rails
Lecture Notes for CS349W
Fall Quarter 2008
John Ousterhout
- Routing: arrange for particular code to be invoked when a URL
arrives in a request:
- Example URL: http://www.mycompany.com/field1/field2/field3?x=14&y=12
- Rails default:
- Invoke method field2 in class Field1Controller,
which is stored in file field1_controller.rb. This method is
called an action .
- The id parameter to the method will have the value field3.
- The query values will be available through the params object
as params[:x] and params[:y].
- Notice the conventions for the names: standard capitalization
and formation of compound names based on a root such as field1.
- Most common pattern for applications:
- The Rails routing mechanism is fairly general and allows you to
define other ways of routing URLs to methods, but the default
mechanism handles most cases.
- Grouping several action methods in one controller is a nice framework:
- Group all of the actions related to a particular kind of data
in a particular class: they will need to cooperate and will
share data and utility methods.
- Some actions may be full-page HTML requests; others may respond to
AJAX requests for fragments.
- An individual method works for any object of the type, so pass
the object identifier as a parameter.
- Previous frameworks (e.g., PHP) separated each action into
a different file or class: made it harder for them to work
together.
- This approach makes particular sense for highly interactive
applications, where there could be dozens of AJAX requests
handling elements of a single page.
- Action method collects and manipulates data from models, then passes
control to a view (template) that generates the HTML (or AJAX)
response for the browser.
- Rails facilities to ease the writing of controllers:
- Session support: already discussed.
- The flash: temporary storage for passing data through a redirection:
- Filters:
- Code that is invoked before or after all of the actions in a
controller:
- E.g. a before filter can check to be sure that the user
is logged in and switch to a login page if not.
- An after filter can modify the generated page (e.g.,
automatic compression).
- Can specify whether a filter runs before, after, or around the
actions.
- Can specify which actions the filter applies to.
- Caching: various facilities for caching all or part of generated
Web pages.
- Not clear how useful this will be for highly interactive
applications: pages are too dynamic.