The Invisible Cloak, SQLs Better Half

My experience as a software engineering student at Flatiron is reminiscent of my 14 years of math class in grade school. It’s not the material that’s similar. It’s the method of teaching. We dive into each a new topic by exploring the “why” of it all — and then work to understand the processes underneath the trunk by learning the arduous manual approach to solving the problem. Only once we have mastered that understanding does the teacher disclose the simple, much more streamline process, flipping the truck closed to expedite things along. Don’t we all love that moment! The discovery of Active Record is a great example of this flipping of the trunk revelation.

Active Record — What is it?

Active Record is a bit mysterious. It’s a wonderful ruby gem that can be easily added to our Gemfile with require ‘active_record or by running gem install ActiveRecord in your terminal. It hangs in the background, paying close attention and helping out when it’s called on, saving us from having to use raw long-winded SQL. It is the Model in the Model — View — Controller (MVC) framework of Rails. As an ORM (Object Relational Mapping), Active Record acts as a bridge between the model and the database, giving objects life. As such, objects in a database carry both data and behavior, intwining logic and data.

Ok, so what does that all mean and why should I care?

Basically, Active Record makes the life of all developers a whole lot easier. It eases the process of creating, reading and using objects whose data is stored in databases. Active Record solves the behavioral problem involved in ensuring that the database keep up with any modifications being made, hence the name. As such, it allows objects to be in charge of loading, saving and reading themselves as they always have the most up to date data.

How should I go about setting up Active Record?

First off, you will want to setup up your MVC framework. The Rails generate command will makes this seamless, creating your model, associated views and controller all in one go. With one simple command and the whole set up is complete. Just include your model name — “Movie” in the example below — along with any columns and their associated data type.

rails g Movie title:string description:string genre:string rating:integer trailer:string

You will want to do this same thing for any other models you want to create. Then, simply seed some data in your seeds.rb file and go ahead and db:migrate and db:seed to finish your setup. If you ever need to change up your database structure, you can run:

#to add a column
rails migration add_ColumnName_to_TableName
#to delete a column
rails migration remove_ColumnName_from_TableName

Migrate and you will see this in your db/migrate file.

class CreateMovies < ActiveRecord::Migration[6.0]
def change
create_table :movies do |t|
t.string :title
t.string :genre
t.string :rating
t.string :description

end end

Once the MVC framework is set up, it is time to establish relationships laid out in your ERD. In facilitating the connection between our database, the seeded data, and our models, we can easily establish relationships between model and tables, using has_many and belongs_to syntax.

Instead of establishing these relationships using iterations and multiples methods, Active Record allows you to shortcut this model relationship building:

Here is how one would go about mapping a many-to-many relationship without the help of Active Record.

class User
def movies {|favorite|}

def favorites {|favorite| favorite.user == self}
class Movie
def favorites {|favorite| favorite.user == self}
def users {|favorite| favorite.user}

Active Record makes the process of object-relationship mapping a whole lot easier

class User < ActiveRecord::Base
has_many :favorites
has_many :movies, through: :favorites
class Movie < ActiveRecord::Base
has_many :favorites
has_many :users, through: :favorites
class Favorite < ActiveRecord::Base
belongs_to :movies
belongs_to :users

How should I go about using Active Record post setup?

Moving from environment and database-model setup, Active Record eases data retrieval with simple finder methods. These include queries that allow you to retrieve single or multiple objects at a time with conditional queries such as Movie.first. Similar to SQL’s SELECT * FROM movies LIMIT 1, Movie.first allows you to access the first instance from the Movie class.

For each object in a class, Active Record automatically creates CRUD methods, allowing you to create, read, update, and delete each instance of a class. For example, you can call .create on a new instance of a class and it will create and automatically save the new instance. Active Record also creates new methods for each column within a table. If a Movie Table has a name column, you can call and the name of the first instance of a movie class will be returned. This becomes particularly useful in increasing awareness of tables, models and general understanding of what data is in your table and how you should go about accessing it:

As databases become big and unwieldy, Active Record queries facilitate accessing specific pieces of information from large databases. The Active Record query that I think is quite useful, especially as databases grow in size, is find_each, an efficient batch processing method. It allows you to retrieve instances of a class in batches of 1000 and returns in blocks one-by-one. The method .find can be called on a class to pick a specific instance of a method based on object_id while .find_by can used to find an instance by other attributes such as name or genre.

How did I use Active Record and why was it a lifesaver?

When I created a simple app of my own, Cinemmaaa, which allows users to browse a curated movie list and conduct CRUD actions of movie, user and favorite class, Active Record made it easy to see what lived in the database. In an instant, I could find out what the first instance of a movie was or whether the relationship between Favorite and Movie was set up properly by calling Movie.second.favorites. I could also quickly figure out if my data had been properly seeded and whether returned what I wanted it to.

Active Record saves time and time is everything in coding. You don’t need to touch raw messy and long-winded SQL. Its queries are easy to write and easy to understand. It’s great for beginners and the pros, alike.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store