Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is Active Record in Ruby on Rails?

In this blog post, we'll be diving into Active Record, one of the key components of the Ruby on Rails web application framework. If you're new to programming or just starting to learn Ruby on Rails, you've come to the right place. We'll be explaining things in simple terms and providing real code examples to help you understand the concepts.

Introduction to Active Record

Active Record is an Object-Relational Mapping (ORM) framework for Ruby on Rails. Without getting too technical, an ORM framework is a way to interact with a database using object-oriented programming instead of writing raw SQL queries. In other words, Active Record lets you work with data from a database as if it were a regular Ruby object.

Imagine you have a large pile of books on your desk, and you want to find a specific book by its title. Instead of going through the entire pile one by one, you could use an index that tells you exactly where the book is in the pile. Active Record is like that index, helping you interact with your data in a more organized and efficient way.

To understand Active Record, we'll be covering several topics:

  • Setting up your environment
  • Creating a model
  • CRUD operations
  • Validations
  • Associations
  • Migrations

Let's get started!

Setting Up Your Environment

Before diving into Active Record, we need to set up our environment. We'll be using Ruby on Rails for this tutorial, so make sure you have it installed on your machine. You can follow the official Ruby on Rails installation guide if you haven't installed Rails yet.

Once you have Rails installed, create a new Rails application by running the following command:

rails new my_active_record_app

This will create a new Rails application in a folder called my_active_record_app. Navigate to the new folder:

cd my_active_record_app

Now, we can start working with Active Record!

Creating a Model

A model in Rails represents a table in your database. For example, if you have a table called books, you would create a model called Book. Models are used to interact with the data in the table, such as adding new records, updating existing ones, or deleting them.

To create a model, run the following command:

rails generate model Book title:string author:string

This command creates a new model called Book with two attributes: title and author. The :string part indicates that these attributes are of type string.

Now, let's take a look at the generated files. Open the app/models/book.rb file, and you'll see the following code:

class Book < ApplicationRecord
end

This is our Book model, which inherits from ApplicationRecord. This is where we'll add any custom logic related to our Book model later on.

CRUD Operations

Now that we have our model, let's take a look at how to perform basic CRUD (Create, Read, Update, and Delete) operations using Active Record.

Create

To create a new record in the database, you can use the create method. This method takes a hash of attributes as an argument and creates a new record with those attributes in the database. Here's an example:

book = Book.create(title: 'The Catcher in the Rye', author: 'J.D. Salinger')

This code creates a new record in the books table with the given title and author.

Read

To read records from the database, you can use various query methods provided by Active Record:

  • all: retrieves all records from the table
  • find: retrieves a record by its primary key
  • where: retrieves records that match specific conditions

Here are some examples:

# Retrieve all books
books = Book.all

# Find a book by its primary key
book = Book.find(1)

# Find all books with a specific author
books_by_author = Book.where(author: 'J.D. Salinger')

These query methods return instances of your model, allowing you to interact with the data as if it were a regular Ruby object.

Update

To update a record in the database, you can use the update method. This method takes a hash of attributes to update and saves the changes to the database. Here's an example:

book = Book.find(1)
book.update(title: 'The Catcher in the Rye (Updated)')

This code updates the title of the book with the primary key of 1.

Delete

To delete a record from the database, you can use the destroy method. This method removes the record from the database. Here's an example:

book = Book.find(1)
book.destroy

This code deletes the book with the primary key of 1 from the database.

Validations

Validations are a way of ensuring that only valid data gets saved to the database. Active Record provides several built-in validation helpers that you can use to easily add validations to your models.

To add validations to your model, you can use the validates method in your model class. For example, if we want to ensure that a book must have a title and an author, we can add the following code to our Book model:

class Book < ApplicationRecord
  validates :title, presence: true
  validates :author, presence: true
end

Now, when we try to create or update a book without a title or author, the operation will fail and an error message will be added to the book object:

book = Book.new(title: '')
book.valid? # => false
book.errors.full_messages # => ["Title can't be blank", "Author can't be blank"]

Associations

Associations are a way of defining relationships between different models. For example, if you have a table called authors, you could create an association between the Book and Author models to indicate that a book belongs to an author and an author has many books.

To create associations, you can use the following methods in your model classes:

  • belongs_to: indicates that a model has a foreign key to another model
  • has_many: indicates that a model has a one-to-many relationship with another model
  • has_one: indicates that a model has a one-to-one relationship with another model
  • has_and_belongs_to_many: indicates that a model has a many-to-many relationship with another model

Here's an example of how to create an association between the Book and Author models:

  1. Generate a new Author model:

rails generate model Author name:string

  1. Add a foreign key to the books table:

rails generate migration AddAuthorIdToBooks author:references

  1. Update the Book and Author models with the association methods:

```ruby # app/models/book.rb class Book < ApplicationRecord belongs_to :author end

# app/models/author.rb class Author < ApplicationRecord has_many :books end ```

Now, you can easily access the related records using the association methods:

book = Book.first
author = book.author

author_books = author.books

Migrations

Migrations are a way of changing the structure of your database over time. Instead of manually writing SQL queries to create or modify tables, you can create migration files that describe the changes you want to make, and Rails will generate the appropriate SQL queries for you.

To create a migration, you can use the rails generate migration command, followed by a description of the changes you want to make. For example, if we want to add a publication date to our books table, we can create a migration like this:

rails generate migration AddPublicationDateToBooks publication_date:date

This command generates a new migration file in the db/migrate folder. Open the file, and you'll see the following code:

class AddPublicationDateToBooks < ActiveRecord::Migration[6.1]
  def change
    add_column :books, :publication_date, :date
  end
end

This code adds a new column called publication_date to the books table. To apply the migration, run the following command:

rails db:migrate

Now, the books table has a new publication_date column, and you can use it in your Book model like any other attribute.

Conclusion

In this blog post, we've covered the basics of Active Record in Ruby on Rails, including setting up your environment, creating models, performing CRUD operations, validations, associations, and migrations. By now, you should have a good understanding of how Active Record works and how to use it in your Rails applications.

Of course, there's much more to learn about Active Record, but we hope this post has given you a solid foundation to build upon. As you continue learning and working with Rails, you'll encounter more advanced features and techniques, but the principles we've covered here will always be relevant.

Happy coding!