Understanding ActiveRecord: How To Use Alias With Relationship Mapping

Laurence Hawelu
3 min readApr 22, 2021

ActiveRecord’s Relationship Mapping is a very powerful tool that really simplifies the table modeling process. It is easy to read and follow, which facilitates an understanding of how things are connected. However, there are certain situations where this can get a little more convoluted and you will need to use aliasing to join your tables.

This blog will go into more detail about how to identify when to use aliasing, a little background about using it with SQL, and how to do this in ActiveRecord.

Identifying When To Use Aliasing

Let’s say that you are building an app that has the following tables:

Users Table
Items Table
Purchases Table

In this set-up we only have Users that we want to use for three other foregin keys: owner_id, seller_id, and purchser_id. Since the foreign key doesn’t match the naming convention for our Users table we will need to use aliasing to make this all work.

Breaking Aliasing Down With SQL

Now that we know how to identify when to use aliasing, let’s break this down using SQL. First let’s see what this would like in SQL without aliasing.

At this point SQL will throw an error because we are joining users in without making unique users for either the purchases or the seller. To fix this, we would have to update this a bit to account for each join of our user table. Below is the updated code to allow for aliasing using “as”:

After adding our aliasing to our SQL, we will now be able to create our table with the information that we are looking for without any errors. This was the result of creating unique instances of users for both the Seller and the Purchaser.

Using Aliasing In ActiveRecord

With our newfound knowledge about SQL, let’s see how we do this same thing in our sample models in ActiveRecord. Below are each of the models based on the tables built in the original example:

Users

Items

Purchases

Conclusion

Getting a better understanding of aliasing really helped me fully see the potential of ActiveRecord. I hope that adding aliasing to your repertoire will help you build bigger and better models as you go along in your ActiveRecord journey.

--

--