If you're interested in learning more about the Rails framework, keep reading. This three-part article series takes an in-depth look at one of its more important aspects, the Active Record. This article is excerpted from chapter four of the book Beginning Rails: From Novice to Professional, written by Jeffrey Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
Working with a Database: Active Record - Active Record Conventions (Page 3 of 4 )
Active Record achieves its zero-configuration reputation by way of convention. Most of the conventions it uses are easy to grasp. After all, they’re conventions, so they’re already in wide use. While you can override most of the conventions to suit the particular design of your database, you’ll save a lot of time and energy if you stick to them.
Let’s take a quick look at the two main conventions you need to know:
Class names are singular; table names are plural.
Tables contain an identity column namedid.
Active Record assumes that the name of your table is the plural form of the class name. If your table name contains underscores, then your class name is assumed to be in CamelCase. Table 4-1 shows some examples.
Table 4-1. Table and Class Name Conventions
Table
Class
events
Event
people
Person
categories
Category
order_items
OrderItem
All tables are assumed to have a unique identity column namedid. This column should be the table’s primary key (a value used to uniquely identify a table’s row). This is a fairly common convention in database design. (For more on primary keys in database design, the Wikipedia entry has a wealth of useful information and links:http://en.wikipedia.org/wiki/Primary_key.)
The belief in convention over configuration is firmly entrenched in the Rails philosophy, so it should come as no surprise that there are more conventions at work than those listed here. You’ll likely find that they all make good sense, and you’ll be able to use them without paying much attention.