Chapter 3. Active Record Basics

In Chapter 1, you learned that Rails is a framework for building database-backed web applications. Active Record handles the database-backed part. Active Record uses convention instead of configuration whenever possible, and uses the capabilities of Ruby to dynamically add attributes and methods to your models based on the contents of the database. But this amazing framework is dead simple. In this chapter, you’ll build a few database classes with a mere handful of lines of configuration code. You’ll also see firsthand how Ruby’s metaprogramming will add methods and attributes to your classes based on the contents and structure of the database. Finally, you’ll use Active Record’s built-in language to validate your code quickly with just a few trivial lines of code. First, a little background is in order.

Active Record Basics

Martin Fowler cataloged the Active Record design pattern in a book called Patterns of Enterprise Application Architecture (Addison-Wesley).[2] The Rails framework is an implementation of that idea. With any Active Record implementation, classes represent database tables, and instances (called record objects) represent database rows. Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. This strategy allows simple designs and straightforward mappings between database tables and application objects.

The Rails implementation of Active Record is like Martin Fowler’s pattern on steroids. The ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.