O'Reilly logo

Rails Cookbook by Rob Orsini

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3. Active Record

Introduction

Active Record provides convenient, programmatic access to the domain layer of your application. It’s a persistent storage mechanism that often interacts directly with an underlying relational database. It’s based on (and named after) a design pattern defined by Martin Fowler in his book, Patterns of Enterprise Application Architecture (Addison-Wesley). Fowler summarizes this pattern as:

An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.

Active Record works by creating an object relational mapping (ORM) between the Ruby objects of your application and the rows and columns of your database. This mapping allows you to interact with your database just as you would interact with any other Ruby object, eliminating the need to use SQL to manipulate your data. Instead of working with database rows, you have Ruby objects, and database columns are simply attributes of those objects that you can read or write using Ruby accessor methods.

The benefits of abstracting direct access to your database with Active Record include the ability to change the database that houses the actual data. Your application isn’t “trapped” with one database forever. With the details of your model contained in Active Record, it is trivial to switch from MySQL to say, PostgreSQL or SQLite.

A domain model consists of data and a set of rules for how that data interacts with the rest of your application. Active ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required