Active Record Is for Database Access

Learn how active record is used for database access in our Rails application.

We'll cover the following

Overview

Although Rails is a Model-View-Controller (MVC) framework, the model layer in Rails is really a collection of record definitions. Models in Rails are classes that expose attributes that can be manipulated. Traditionally, those attributes come from the database and can be saved back, though we can use Active Model to create models that aren’t based on database tables.

No matter what else goes into a model class, it mostly certainly exposes attributes for manipulation, like a record or struct does in other languages. As outlined in the “Business Logic” chapter, that’s all the logic that should go in these classes.

When we follow that guidance, the classes in app/models (the model layer) become a library of the data that powers our app. Some of that data comes directly from a database, and some doesn’t, but our model layer can and should define the data model of our app. This data model represents all the data coming in and going out of our app. The service layer discussed in the business logic chapter deals with these models.

This chapter will cover the basics around managing that. We’ll talk about Active Records and their unique place in the Rails architecture, followed by Active Model, which is a powerful way to create Active Record-like objects that work great in our view. Let’s start with accessing the data in our database using Active Record.

What is Active Record for?

With two lines of code, an Active Record can provide sophisticated access to a database table in the form of class methods for querying and a record-like object for data manipulation. It’s one of the core features of Rails that makes developers feel so productive.

In our experience, when we place business logic elsewhere, we don’t end up needing much code in our Active Records. Those few lines of code we do need are often enough to enable access to all the data our app needs. That said, there are times when we need to add code to Active Records. The three main types of code are:

  • Additional configuration such as belongs_to or validates.
  • Class methods that query the database and are needed by multiple other classes to reduce duplication.
  • Instance methods that define core domain attributes whose values can be directly derived from the database without the application of business logic.

Let’s dig into each of these a bit, but first, we need some Active Records to work with.

Get hands-on with 1400+ tech skills courses.