Taking a Load Off with ActiveRecord
Published: 2020-11-28 01:49:49

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"
```

and with ActiveRecord:
```
User.create(name: "Joe Everyone")
User.find_by(name: "Joe Everyone")
```

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
```
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
```

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)
);
```

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
```
With ActiveRecord we can very simply write:
```
user = User.find_by(id: params[:id])
user.posts
```

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!


<span>Photo by <a href="https://unsplash.com/@alesme?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ales Me</a> on <a href="https://unsplash.com/s/photos/relax?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>