Chapter 2. Active Record Basics

Active Record, which controls the interaction between your application and the database, is the heart of Rails. Active Record’s elegant simplicity almost completely eliminates the need for configuration; in this chapter, you’ll see how Active Record’s conventions reduce your configuration from hundreds of lines to a handful. You’ll also see how Active Record’s metaprogramming dynamically adds capabilities to your classes, based on the contents and structure of the database. Finally, you’ll use Active Record’s elegant extensions of Ruby to quickly validate your code with less effort than ever before.

Active Record Basics

Martin Fowler cataloged the Active Record design pattern in a book called Patterns of Enterprise Architecture.[*] The Rails framework is an implementation of that idea. With any Active Record implementation, users manipulate database tables through record objects. Each record represents a row in a database table, and 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 persistence framework is like Martin Fowler’s Active Record on steroids. The Rails version adds some capabilities that extend Active Record. Table 2-1 shows a list of critical differences, followed by the benefit to the developer.

Table 2-1. Rails versus Active Record

Difference

Benefit

Rails adds attributes ...

Get Ruby on Rails: Up and Running now with the O’Reilly learning platform.

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