Course contentsShow
← Software Engineering
Lesson 935 of 1,93329. Object-Relational MappingFree lesson

Active Record Pattern

Encapsulating database row data and behavior in a single object that knows how to persist itself.

Active Record Pattern

What you'll learn: How to model a database row as an object that knows how to save, update, and delete itself.

The Core Idea

The Active Record pattern encapsulates both data and behavior in a single object that represents a row in a database table. Unlike separating your data structures from your database logic, an Active Record object knows how to persist itself—it carries its own CRUD (Create, Read, Update, Delete) methods.

Think of it like a smart business card: instead of handing someone a piece of paper and a separate filing cabinet manager, you give them a card that can file itself, update itself, and even delete itself from the drawer.

How It Works

Each Active Record object corresponds to one row in a database table. The object's attributes mirror the table's columns, and the object itself contains methods like save(), update(), and delete() that interact directly with the database.

For example, if you have a User table with columns id, name, and email, your User Active Record object would have those same attributes plus methods:

  • user.save() — inserts or updates the row
  • user.delete() — removes the row
  • User.find(id) — retrieves a row by ID

This pattern directly addresses the navigational access pattern we discussed earlier: you navigate through objects using their methods, and each object manages its own persistence.

When to Use It

Active Record works beautifully when your object structure closely mirrors your database schema—when there's minimal impedance mismatch. It's widely used in frameworks (like Ruby on Rails' ActiveRecord) for straightforward domain models where business logic and persistence naturally live together.

Key Takeaway: Active Record unifies data and database behavior in a single object that represents a table row and knows how to persist itself, ideal when your objects map cleanly to database tables.