DEV Community

Fikredeyas
Fikredeyas

Posted on

Active Record - brief introduction for beginners

Image description

Active Record: What is it?
Let's take a moment to briefly explain the purpose of Active Record if you are unfamiliar. We deal with classes and objects in Ruby because the language adheres to the object-oriented paradigm. In most circumstances, we have a relational database at our disposal, even if it would have been good to work with some object-oriented database in conjunction with our object-oriented Ruby classes.

You will use ActiveRecord methods throughout the whole development process of a Ruby on Rails app, starting from scratch. There are a lot of them, and it's beneficial to get to know them well (if not by heart).

Even though practically everyone employs AR techniques to create almost all apps, there are still a lot of techniques that are not well-known. Many of these can keep your code tidy and save you time (and, to be honest, sometimes even your stress). Some helpful instances that are wise to be familiar with can be found below.

Image description

With a focus on retaining the ability to audit the changes made to a database, migrations offer an organized approach of adding and changing database tables. While manually creating migration files is possible, doing so necessitates keeping in mind the specific order of the migrations, prefixing filenames with, for example, 01_, 02_, 03_, etc., and being extremely careful to stick to a numerical pattern. If we have a lot of migrations to maintain, this might get very laborious.

We may utilize the Rake gem, install it, and define it in our Gemfile to expedite the creation of migrations. Then, having the correct filename, we can simply run the following command in a Terminal window:

rake db:create_migration NAME=create_artists

Image description

For every database table, maintain a separate migration file.
While handling numerous database table migrations with a single migration file may seem appealing, it is not recommended for a number of reasons. For instance, if we need to subsequently modify a particular table, dealing with several table migrations in a single migration file makes troubleshooting more difficult.

Top comments (0)