As Ruby on Rails is a Full-Stack Framework so having a good understanding of databases is essential Right.
Normally, you’d need to write SQL queries to manage database interactions, like fetching or updating records.
But Rails makes this process much easier with Active Record, It is a built-in tool that connects your database to Ruby objects.
Instead of writing complex SQL queries, you can work directly with Ruby code. This not only simplifies your code but also makes it more readable, maintainable, and scalable.
Active Record is the M
in the MVC (Model-View-Controller) framework. It represents the model layer, which deals with the data and business logic of your Rails app.
This means that you can focus on building features instead of managing complex database queries, Amazing Right? Let's learn more about it.
What is Active Record?
At its core, Active Record is an Object Relational Mapper (ORM). This means it helps connect Ruby objects to database tables. It's like a translator between your Ruby code and the database.
When you create a new Rails model, like User, Active Record automatically links it to a database table named users.
Each row in that table becomes a Ruby object, and the table’s columns become the object's attributes.
It is like:
- If your database has a table for users, Active Record creates a User class in Ruby to represent it.
- Each row in the users table becomes a Ruby object that you can interact with in your code.
For example:
ruby
user = User.find(1)
puts user.name
Here, instead of writing a SQL query like SELECT * FROM users WHERE id = 1
, Active Record allows you to use Ruby methods to achieve the same thing.
How Active Record Works
Active Record follows a design pattern called the Active Record Pattern. This pattern was popularized by Martin Fowler, who described it as:
An object that wraps a row in a database table, encapsulates the database access, and adds domain logic to that data.
In simple words, it means that each Ruby object represents a row in a database table and gives you tools to interact with the database.
Key Features of Active Record
- Encapsulation of Data
Active Record wraps each database row as a Ruby object. This allows you to treat database records like regular Ruby objects with methods and attributes.
- Object-Relational Mapping (ORM)
Active Record is an ORM system. It connects the tables in your database with Ruby classes, making it easier to manipulate data using Ruby instead of SQL.
- Automatic SQL Generation
You don’t need to write SQL manually. Active Record generates SQL queries behind the scenes for basic operations like fetching, creating, updating, and deleting records.
Active Record vs. Active Model in Simple
Active Record and Active Model are both part of the Model layer in Rails, but they serve different purposes:
- Active Record is used when your data needs to be saved in a database.
- Active Model is used for Ruby objects that don’t require a database.
For example, if you’re collecting user input from a form but don’t need to store it in a database, you can use Active Model. Active Record is better when you need to read from or save data to a database.
How Active Record Maps SQL to Ruby
Let’s see how Active Record translates SQL into Ruby objects in simple with easy examples. Let’s say you have a users
table with the following data:
id | name | |
---|---|---|
1 | Alice | alice@example.com |
2 | Bob | bob@example.com |
Fetching Data with SELECT Command
In raw SQL, you would write:
sql
SELECT * FROM users;
With Active Record, you can do the same using:
ruby
users = User.all
This returns a collection of User
objects, where each object represents a row from the users
table.
ruby
users.each do |user|
puts user.name
end
Finding a Specific Record with WHERE Command
To find a user with a specific email, you might write:
sql
SELECT * FROM users WHERE email = 'alice@example.com';
In Active Record:
ruby
user = User.find_by(email: 'alice@example.com')
puts user.name # Output: Alice
Creating Data with INSERT Command
To add a new user in SQL:
sql
INSERT INTO users (name, email) VALUES ('Charlie', 'charlie@example.com');
In Active Record:
ruby
user = User.new(name: 'Charlie', email: 'charlie@example.com')
user.save
Updating Data with UPDATE Command
To update a user’s email:
sql
UPDATE users SET email = 'alice_new@example.com' WHERE name = 'Alice';
In Active Record:
ruby
user = User.find_by(name: 'Alice')
user.update(email: 'alice_new@example.com')
Deleting Data with DELETE Command
To delete a user in SQL:
sql
DELETE FROM users WHERE name = 'Bob';
In Active Record:
ruby
user = User.find_by(name: 'Bob')
user.destroy
Let's Build a Simple Example Blog
Let’s create a basic blog with Post
and Comment
models.
- Post Model (
posts
table):
```
ruby
class Post < ApplicationRecord
has_many :comments
end
2. **Comment Model** (`comments` table):
ruby
class Comment < ApplicationRecord
belongs_to :post
end
Now you can easily fetch all comments for a post:
ruby
post = Post.find(1)
comments = post.comments
Without writing any SQL, you get all comments associated with the post.
For more detailed documentation, you can check out the official [Rails Guides on Active Record](https://guides.rubyonrails.org/active_record_basics.html).
Let me know the feedback in comments below, Thanks