Active Record: Quick Start!

RMAG news

👋 Hello fellow learner!

 
As I dive into Rails for the first time with the Odin Project, I’m learning just how cool (and a bit confusing) Active Record can be. I decided to write this post to help my future self remember the basics and to share what I’ve learned with others. Think of it as a quick reference to getting started with Active Record without the fuss. It highlights a few elements of Active Record that I thought were particularly important.

Hope this helps clear things up and makes your Rails journey a bit smoother!

 

What is Active Record?

Active Record is the part of Rails that handles the database and connects it to your application. Creating tables, altering schemas, and formulating queries requires a certain level of complexity and a lot of configuration code. Rails handles all of that for us with Active Record and simplifies the process of interacting with our database. It is almost like a translator between Ruby and basically any database language.

 

What does Active Record do?

Takes the app data from the rows and columns in your database
Allows you to interact with the data as a Ruby object

It is like magic!—like a little middleman between you and your database that handles writing and executing all of the queries you would otherwise have to type out yourself. Instead, you provide it with something written in Ruby (which is much easier to write, read, and understand, IMHO), and it translates that into the language of your database and returns the result you’re looking for.

So how does Active Record know what kind of database you are using?
You basically give Active Record some basic information about your database via the config/database.yml file, and it handles the rest. That means if you end up switching databases later on, you should theoretically only have to change the configuration info. Is this what they mean by 🚃 The Rails Way 🚃?

It seems pretty nice honestly…

How does this look on a Rails app?
We’ll use a super simple blog app deployed via Railway as an example.

Information about the articles on the blog are stored in a database table called articles. The model used to access that data is called article, in keeping with the Rails singular/plural configuration.

The model is simply a Ruby object…

class Article < ApplicationRecord

end

…that inherits from ApplicationRecord which in turn inherits from ActiveRecord.

class ApplicationRecord < ActiveRecord::Base
primary_abstract_class
end

So there’s the connection! And it is easy to see thanks to Ruby.

 

Naming conventions

This isn’t just to make your code look pretty. Rails emphasizes “convention over configuration” to help lighten the load on developers. Instead of having to write out lots of lines of configuration code to get your application to work, just hop onboard the Rails wagon 🚃 and do it like they say to.

Rails will automatically pluralize your model’s class names. In our case, the model was class Article, so the database table is called articles as you can see in our articles controller:

class ArticlesController < ApplicationController
def index
@articles = Article.all
end

def show
@article = Article.find(params[:id])
end

# etc…
end

Rails uses the Active Support library to accomplish this. So it is not magic, nor is it simply adding an ‘s’ on at the end. (e.g., Person gets mapped to people automatically.)

 

Creating an Active Record model

When you create a new Rails app and generate your first model, the ApplicationRecord class is created and placed in the app/models directory. As we saw before, ApplicationRecord inherits from ActiveRecord::Base. So to create a new Active Record model, you just create a new class that inherits from Application Record. Remember to make your class name singular!

class Article < ApplicationRecord
end

When you do this, Rails creates a Article model that is mapped to a articles table in the database. Each column of the table will be mapped to an attribute of the Article class. An instance of the Article class represents a single row in the articles database table.

But where is the table? Is it created already?
Rather than creating the table via a CREATE TABLE SQL statement that explicitly defines all of the column headers and their types, you just use an Active Record migration on the command line.

$ bin/rails generate migration CreateArticles title:string body:text
class CreateArticles < ActiveRecord::Migration[7.2]
def change
create_table :articles do |t|
t.string :title
t.text :body

t.timestamps
end
end
end

$ bin/rails db:migrate

Another example of hopping on the Rails wagon 🚃 and letting it do its thing.

 

CRUD and Active Record

Rails is built around the idea that most applications operate on data in four ways: Creating, Reading, Updating, and Deleting (CRUD). This is so ingrained in Rails that when you create a new Active Record, Rails automatically provides a set of built-in methods to make it super easy to perform CRUD operations.

Each of these methods results in the creation and execution of SQL statements behind the scenes. Rails also provides plain English ways of accessing these methods, making it even easier to connect with your records. 🚃 Hop Aboard!

What you see: articles = Article.all

What goes on behind the scenes: SELECT “articles”.* FROM “articles”

 

Summary

Active Record is a fantastic tool, though it can be confusing when you’re first learning it. But the takeaway is that Active Record handles a lot of the heavy lifting, syntax, and configuration, allowing us to interact with our database via Ruby objects. When in doubt, hop on board the Ruby wagon 🚃 and let Active Record do what it is meant to do: make our lives easier as developers.

 

Helpful Links

The Odin Project
Rails Guides: Active Record Basics

 

 
👋Connect with me on Github or LinkedIn.
I’d love to hear your thoughts!

Please follow and like us:
Pin Share