Basic Active Record Classes

As you create new database tables, you’ll want to use a couple of common naming conventions. The table name photos and the definition of the id column are both significant. (With our migration, Rails created the id column automatically.) Rails uses several naming conventions:

Class and table names

If the name of your database tables is the English plural of the name of your model class, Rails can usually infer the name of the database table from the name of the Active Record class. (Active Record will have trouble with some irregulars such as moose, but supports many popular irregulars such as people.)

Identifiers

Similarly, Active Record automatically finds a column called id and uses it as a unique identifier. The id column should be an integer type and be populated by the database. In this case, the migration creates a SQLite auto-increment sequence. Staying with these conventions saves you some configuration, and it also makes your code much easier to understand.

Foreign keys

Foreign keys should be named <class>_id. For example, our slides table will have a foreign key named photo_id to refer to a row in the photos table.

Capitalization

When you’re defining a class, use standard Ruby conventions. Capitalize the first letter of each word and omit spaces between words (commonly called camel casing). But Rails methods, database table names, columns, attributes, and symbols use underscores to separate words. These conventions are mostly cosmetic, but Rails ...

Get Rails: Up and Running, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.