Lesson Weekend

So far, our record store database just has an albums table. That's fine for now. We'll add a songs table and make an association between the two tables in the next lesson.

First, we need to set up our business logic. Remember all that business logic in the Album class in the last section? That logic belongs in app/models where our models are stored.

A model is the M in MVC. Models contain business logic that interacts with the database. Business logic that doesn't interact with a database doesn't belong in a model.

We'll need CRUD logic for our new application, ranging from an Album.find method to an Album#delete method. First, let's create a new model in app/models called album.rb. Here's the code we'll add:

class Album < ApplicationRecord

That's it. Our Album class inherits from ApplicationRecord. There is a file called application_record.rb in our models folder. If we take a look, we'll see that ApplicationRecord inherits from ActiveRecord::Base, which automatically creates all CRUD functionality for the class. We don't need to write these methods. We don't have to test them, either, because Active Record is thoroughly tested.

Once again, naming is very important for Active Record to work. Active Record is automatically creating these methods and making associations between our database tables and classes. If we don't follow naming convention, Active Record will fail to make the correct associations between our classes and tables.

Active Record requires that our class names be the singular, upper-camel-case form of our table names. The names of our models should be the lower-snake-case form of your class names. The Album class is backed by the albums table and written in the album.rb file. Similarly, a CuteKitten class would be backed by the cute_kittens table and be in a file called cute_kitten.rb.

We haven't added much code to our model yet. That's because Active Record does so much for us. This gives us more time to work on other business logic such as validations, callbacks and scopes. We will cover all of these things in future lessons.

Before we continue on, we'll cover one more thing. What is the point of having an application_record.rb file? This file provides a place to put code that all of our models inherit. We won't be putting any code in this file while we work with Rails, but it's good to know why the file exists.

Lesson 5 of 34
Last updated July 14, 2022