Object-Relational Mapping and the Beauty of Active Record
What’s object-relational mapping, or ORM? Although it sounds complicated, it is simply the ability to access relational databases while using an object oriented programming language. This way, we can use OOP to “map” database tables to classes and and database rows to instances of those class. In other words, we are converting database data to objects that can be used within an OOP. If I want an array of all users in a given database, I would have to incorporate SQL into my code to make that request. Let’s take a look at what manually mapping data looks like.
As you can see above, there are plenty of methods to accomplish the task of mapping data from our database. There’s a .create_table method, a .drop_table method, and also a method to save the data into the database. But….this is a little wordy isn’t it? What if there was a way to accomplish the same task but with less lines of code? This is where Active Record comes in!
The Benefits of Active Record
Typically, data is the most important aspect of a web application. Naturally, how we handle that data should be of much importance. Active Record is a gem that will make our lives so much easier. It can give us the ability to structure data and models for our users in a plain and easy-to-understand way. Moreover, it provides us a plethora of different functionalities, such as representing data, performing database functions, validating models before they are persisted to the database and so much more. Take another look at the code above, and then take a look at the code below.
Look at the ease in which we are able to create a table! This code is by far much more succinct and we don’t even need to write SQL! It is important to note that within Active Record, these migrations are only run once, so in case we need to alter this table in any way, we would need to create a new migration, which is just as simple. Once the code is to your liking, be sure you are inheriting from ActiveRecord::Migration and to run rake db:migrate once you are ready. In your model class, your code will be inheriting from ActiveRecord::Base (see below photo). The use of rake is simply a task management tool for Ruby. Just ensure you create a Rakefile in your directory.
I have nothing against SQL — I actually enjoy it. But, you cannot ignore the ease and simplicity Active Record will provide. Make your code cleaner to read and understand with Active Record!