The previous chapter showed how Rails makes it easy to create simple applications using scaffolding, but a key aspect of Rails scaffolding is that it isn’t meant to be permanent. This doesn’t necessarily mean that you’ll tear it down completely and start over, but it usually means that you’ll at least make substantial improvements to make it more attractive. This is especially important where information is coming in from users. While Rails scaffolding provides basic functionality, you’re very likely going to want to improve on the forms it creates.
To demonstrate a reasonably complete set of HTML form features, the application needs to support more than one data field and needs to support fields in a variety of different types. Rails, because it works with a wide variety of databases, supports a narrower set of types than each of those databases. The types of fields that Rails supports through ActiveRecord include:
:string :text :integer :float :decimal :datetime :timestamp :time :date :binary :boolean
The :string
type is generally limited to 255 characters, whereas
:text
can hold longer data. The
:integer
, :float
, and :decimal
types all hold numbers, although
integers may not have a fractional
part to the right of the decimal point. The :datetime
, :timestamp
, :time
, and :date
types hold the classically complicated
combination values used to represent dates and times. The :binary
type can hold unstructured binary
data, often called BLOBs for Binary Large Objects. (You’ll need to
decide how you want to handle binary data—just stuffing it into a database isn’t always
the right answer.) Finally, the :boolean
is the simplest type, accepting only
the values of 0 and 1, equal to true
and false
.
HTML forms offer a variety of ways to enter data that doesn’t map one-to-one to the data types Rails uses:
Text fields (normal, hidden, and password)
Text areas
Checkboxes
Radio buttons
Selection lists (including multiple selections and grouped selections)
File uploads
Other buttons (submit, reset)
To demonstrate how these pieces work with ActiveRecord data types, we’ll create an application with the following data fields:
Name, secret, country, email
Description
“Can we send you email?”
An integer for specifying graduation year, a floating-point number for body temperature, and a decimal for price
The user’s birthday and a favorite time of day
File uploads deserve separate coverage, so we will explore them in Chapter 8 in the section Adding a Picture by Uploading a File.”
Yes, these choices are somewhat whimsical, but they’ll provide a framework in which to explore how Rails supports data types and how you can build on that support.