DEV Community

Cover image for Taking a Load Off with ActiveRecord
Ronnie
Ronnie

Posted on • Updated on

Taking a Load Off with ActiveRecord

ActiveRecord is the ORM layer Ruby on Rails supplies to an application. Most simply put, ActiveRecord is the 'M' in MVC. Models are the system responsible for representing the application's logic. ActiveRecord saves us a lot of time that could be spent writing database query commands, think SQLite, Postgres, MySQL...

ActiveRecord maps a table to a database making each row of data and instance of a class and makes all of our database queries simple, neat and quick (ORM).

Let's see the difference between adding a row to a database table and finding that row or instance in the table with an SQL query:

INSERT INTO Users (name)
VALUES ("Joe Everyone")

SELECT * FROM Users
WHERE name="Joe Everyone"
Enter fullscreen mode Exit fullscreen mode

and with ActiveRecord:

User.create(name: "Joe Everyone")
User.find_by(name: "Joe Everyone")
Enter fullscreen mode Exit fullscreen mode

This isn't saving us TOO much time, but what happens when we have a lot more parameters for an instance of the User class, name, DOB, location, do they have a premium account?...

The real magic happens when we get into the relationships and associations between models.

User model and migration table:

class User < ActiveRecord::Base
  has_many :posts
end

class CreateUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :users do |t|
      t.string :name
      t.string :email
      t.string :avatar_url
      t.integer :post_ids
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Let's say these users are blogging, so we'll create a Post class and migration table as well:

class Post < ActiveRecord::Base
  belongs_to :user
end

class CreatePosts < ActiveRecord::Migration[5.2]
  def change
    create_table :posts do |t|
      t.string :title
      t.text :content
      t.date :post_date
      t.integer :user_id
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Let's see what writing these tables would look like as SQL queries:

CREATE TABLE User
(
Pk_User_Id INT PRIMARY KEY,
Name VARCHAR(20),
Email VARCHAR(20),
Avatar_Url VARCHAR(20)
);

CREATE TABLE Post
(
Pk_Post_Id INT PRIMARY KEY
Title VARCHAR(50),
Content TEXT,
Post_date DATE,
Fk_User_Id INT FOREIGN KEY REFERENCES User(Pk_User_Id)
);
Enter fullscreen mode Exit fullscreen mode

Starting to look like some heavy lifting on the SQL side. Now, let's say we want to see all of the posts from a certain User

With SQL, we'll need write an Inner Join:

SELECT *
FROM Users
INNER JOIN Posts
WHERE User.Pk_User_Id = Post.Fk_User_id
Enter fullscreen mode Exit fullscreen mode

With ActiveRecord we can very simply write:

user = User.find_by(id: params[:id])
user.posts
Enter fullscreen mode Exit fullscreen mode

This gets increasingly more complicated as we start adding more models and relationships.

Additionally, ActiveRecord automatically creates methods to make using CRUD verbs simple and intuitive. We can also use ActiveRecord to validate a model before an instance is persisted to the database. We wouldn't want two users to have the same email address, or a post to have no content!

ActiveRecord is not only a powerful tool, but pretty fun to use! Happy persisting!

Photo by Ales Me on Unsplash

Top comments (0)