Lecture 12 - February 20
Layouts/Flash/Validation
A complete demo (the app and public folders) of the final school project
including the layouts and model validation discussed in class is available in
this zip.
We can use layouts to create a consistent look and feel for every view.
Remember that Rails requires separate CSS files to be stored in
public/stylesheets so that this <%= stylesheet_link_tag
'something'> can find the file something.css.
There are three hashes (Mark says maps) that we've used so far:
- params - gets data from forms and from the URL
- session - contains session data (implemented with a cookie).
Since sessions persist across request/responses, they provide a way to
communicate state information across multiple requests.
- flash - persists only across one redirect. If you need to save
across an additional redirect, use
flash.keep
With respect to validation, we validate in the model for properties that each
field should possess (e.g., validates_numericality_of) as well as
properties of objects in the model (e.g., validates_uniqueness_of).
The validation methods can be found on pages 363-369 of the textbook.
Remember if you don't want to let the user embed html when you print out a
table value they they inputted, just call h in the view. For
example, if I wanted to prevent this in the list view for student names, I
would write
<%= h student.name %>.
Another cute view helper that we didn't mention in lecture is the
pluralize helper. If you need to print a number followed by a noun and
want the noun to agree in the plural (like 1 student, 5 students), you can use
the pluralize helper. For example, <%= pluralize(5, 'student')
%> will print "5 students". Obviously, "5" and 'student" can be
replaced by appropriate variables.
The demo failure toward the end of lecture was due to cookies being disabled
in the browser for some unknown reason! As Rails uses cookies to store
session info (like the authentication token to prevent request forgery), this
caused the behavior we saw. Moral of the story - don't disable cookies!