Active Record Basics

Sekou Dosso
4 min readOct 19, 2020

Active Record

Active Record is the M in MVC — the model — which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.

The Active Record pattern

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

An object carries both data and behavior. Much of this data is persistent and needs to be stored in a database. Active Record uses the most obvious approach, putting data access logic in the domain object. This way all people know how to read and write their data to and from the database.

Object Relational Mapping

Object Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.

Note: Basic knowledge of relational database management systems (RDBMS) and structured query language (SQL) is helpful in order to fully understand Active Record.

Active Record as an ORM Framework

Active Record gives us several mechanisms, the most important being the ability to:

  • Represent models and their data.
  • Represent associations between these models.
  • Represent inheritance hierarchies through related models.
  • Validate models before they get persisted to the database.
  • Perform database operations in an object-oriented fashion.

Naming Convention

By default, Active Record uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class Book, you should have a database table called books. The Rails pluralization mechanisms are very powerful, being capable of pluralizing (and singularizing) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the CamelCase form, while the table name must contain the words separated by underscores. Examples:

  • Model Class — Singular with the first letter of each word capitalized (e.g., BookClub).
  • Database Table — Plural with underscores separating words (e.g., book_clubs).

Schema Conventions

Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns.

  • Foreign keys — These fields should be named following the pattern singularized_table_name_id (e.g., item_id, order_id). These are the fields that Active Record will look for when you create associations between your models.
  • Primary keys — By default, Active Record will use an integer column named id as the table’s primary key (bigint for PostgreSQL and MySQL, integer for SQLite). When using Active Record Migrations to create your tables, this column will be automatically created.

Creating Active Record Models

It is very easy to create Active Record models. All you have to do is to subclass the ApplicationRecord class and you’re good to go:

class User < ApplicationRecord

end

Rails has a nice syntax to generate model:

example: rails generate model User username:string password:string

Above will create a User model, mapped to a User table at the database. By doing this you'll also have the ability to map the columns of each row in that table with the attributes of the instances of your model.

Migrations

Rails provides a domain-specific language for managing a database schema called migrations. Migrations are stored in files which are executed against any database that Active Record supports using rake. Here's a migration that creates a table:

Rails keeps track of which files have been committed to the database and provides rollback features. To actually create the table, you’d run rails db:migrate and to roll it back, rails db:rollback.

Note that the above code is database-agnostic: it will run in MySQL, PostgreSQL, Oracle, and others. You can learn more about migrations in the Active Record Migrations guide.

Validations

Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format, and many more.

Validation is a very important issue to consider when persisting to the database, so the methods save and update take it into account when running: they return false when validation fails and they don't actually perform any operations on the database. All of these have a bang counterpart (that is, save! and update!), which are stricter in that they raise the exception ActiveRecord::RecordInvalid if validation fails.

--

--