All Pages All Books|
|
|||
|
belongs_to :category
validates_associated :category
validates_format_of :done_before_type_cast, :with => /[01]/, :message=>"must be 0 or 1"
validates_inclusion_of :priority, :in=>1..5, :message=>"must be between 1 (high) and 5 (low)"
validates_presence_of :description
validates_length_of :description, :maximum=>40
validates_format_of :private_before_type_cast, :with => /[01]/, :message=>"must be 0 or 1" end
Validating Links between Tables
• the use of belongs_to and validates_associated links the Items table with the item_id field in the Category table.
|
|||
|
|
|||
|
Documentation: ActiveRecord::Associations::ClassMethods
|
|||
|
|
|||
|
Validating User Input
|
|||
|
|
|||
|
|
validates_presence_of protects ‘NOT NULL fields against missing user input
validates_format_of uses regular expressions to check the format of user input
when a user types input for a numeric field, Rails will always convert it to a number – if all else fails, a zero. If
you want to check that the user has actually typed in a number, then you need to validate the input
_before_type_cast, which lets you access the ‘raw’ input5.
validates_inclusion_of checks user input against a range of permitted values
validates_length_of prevents the user entering data which would be truncated when stored6.
|
||
|
|
|||
|
|
|||
|
|
|||
|
|
|||
|
|
|||
|
Documentation: ActiveRecord::Base
More on Views
Sharing Variables between the Templates and the Layout
By now, it is becoming obvious that all my templates will have the same first few lines of code, so it makes sense to move this common code into the layout. Delete all the app\views\layouts\*.rhtml files, and replace with a common application.rhtml.
app\views\layouts\application.rhtml
<html> <head>
<title><%=h @heading %></title>
<link href="/stylesheets/ToDo.css" rel="stylesheet" type="text/css" /> </head> <body>
<h1><%=h @heading %></h1> <% if @flash["notice"] %> <span class="notice">
<%= @flash["notice"] %> </span> <% end %>
<%= @content_for_layout %> </body> </html>
I’ve renamed the public/stylesheets/acaffold.css to ToDo.css for tidiness, and also generally played with colours, table borders, to give a prettier layout. However, returning to Rails, note how the heading variable is shared between the two files, which means that you can have content in the layout dynamically defined by a template:
|
|||
|
|
|||
|
5 What might seem a more obvious alternative: validates_inclusion_of :done_before_type_cast, :in=>"0".."1", :message=>"must be between 0 and 1" – fails if the input field is left blank
6 You could however combine the two rules for the Description field into one: validates_length_of :description, :within => 1..20
|
|||
|
|
|||
|
Page 16
|
|||
|
|
|||
All Pages All Books