Active Record: Your Object is the Database Row
The Active Record pattern treats an object as a self-managing database row, bundling data with persistence logic. It's great for simple CRUD apps, but tightly couples your business logic to your database schema, making complex refactors difficult.
WHY IT EXISTS To reduce the boilerplate code needed to move data between a database and application objects. Instead of writing separate data access layers and manually mapping SQL results to objects, you interact with the database directly through methods on the object itself, speeding up development for simple cases.
THE MENTAL MODEL Think of an object as a self-aware database row. It doesn't just hold data like a plain data structure; it knows how to write itself to the database, update its corresponding row, and delete itself. The object is responsible for its own persistence.
HOW IT WORKS An Active Record class maps directly to a database table, and an instance of that class corresponds to a single row. The object's properties map to the table's columns. The interface includes methods for persistence, such as save() (for inserts/updates), update(), and delete(). For example, creating a new object and calling save() on it would generate and execute an SQL INSERT statement behind the scenes.
WHEN TO USE IT Active Record shines in applications with a heavy focus on Create, Read, Update, Delete (CRUD) operations and where the application's object model closely mirrors the database schema. It is excellent for rapid prototyping and building straightforward systems like blogs, simple e-commerce sites, or content management systems.
WHEN NOT TO USE IT Avoid Active Record in complex applications where the business logic and database schema need to evolve independently. The pattern tightly couples your domain objects to the database structure, which means a schema change can easily break application code. This coupling also violates the Single Responsibility Principle, as the object is now responsible for both business logic and data persistence, leading to bloated, hard-to-test classes.
ONE CANONICAL EXAMPLE Ruby on Rails' ActiveRecord is the most famous implementation. A User model inherits from ActiveRecord::Base. You can create a new user with user = User.new(name: 'Alice') and persist it to the database by calling user.save(). To update, you change a property and call save() again: user.name = 'Alicia'; user.save().
Read the original → en.wikipedia.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.