Active Record
Active Record wraps a database row in an object that holds both its data and the methods to persist itself. It is simple and fast for CRUD-heavy apps with schema-aligned models but couples domain logic to the database and bloats as logic grows.
Active Record is a data-access pattern in which an object wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data. Each Active Record object carries both the data of a row and the behavior to persist itself: methods like save, delete, and finders live directly on the model. The object and the table row map almost one to one.
How It Works
A class corresponds to a table, an instance corresponds to a row, and the object's properties correspond to the columns. The class provides static or class-level finder methods, such as find or where, that query the table and return populated instances. Instances provide instance methods like save, which inserts or updates the row, and delete. Business logic that operates on a single record is often added to the same class, so data and behavior live together.
This tight coupling makes the pattern intuitive and fast to develop with. Frameworks like Ruby on Rails, Laravel's Eloquent, and Django's ORM are well-known Active Record implementations.
When to Use It
Use Active Record when the domain model maps closely to the database schema, when the application is largely CRUD with modest business logic, or when development speed and simplicity matter more than strict separation of concerns. It shines in rapid application development and for straightforward data-driven features.
Trade-offs
Because persistence is baked into the model, the pattern couples domain objects to the database schema, which makes unit testing harder without a database and complicates supporting rich domain models or multiple data sources. As business logic grows, models can become bloated god objects mixing data, persistence, and behavior. When the object structure diverges from the schema, the Data Mapper pattern, which separates the two, scales better. Active Record also tends to encourage per-record saves rather than batched transactions.
Related Patterns
Data Mapper is the direct alternative, separating persistence from the domain object for richer, more testable models. Repository can wrap Active Record models to provide a cleaner domain interface. Unit of Work is harder to apply because Active Record favors immediate, per-object saves.
Example
A User model in a Rails-style framework offers User.find(id) to load a row and user.save to persist changes, with validation and simple business rules defined on the model. A new feature reads, modifies, and saves users in a few lines, which is ideal while the model stays close to its table and the logic remains modest.