Active Record Associations

Jakob Persons
7 min readDec 23, 2020

What are Associations in the world of Active Record?

If you’re familiar with Active Record, then you’re familiar with Ruby and object oriented programming languages. Object oriented languages like Ruby allow relationships that exist within the real world to be represented within your code as a programmer! Kind of like your Sims character and your life…or mine.

Let’s use an example for some context. Say you are a best selling author, you probably have many books, articles, short stories, poems, etc. However, each one of your books belongs to you. Additionally, your book has a genre. That genre, however, has many books that fall underneath its ‘umbrella’.

What we’re trying to say is that you as an author, can have many books. Each genre, can also have many books. However, each book belongs to an author, and a genre. Now, we have just realized some associations that we can portray using Ruby and Active Record within our programming, how are these associations displayed though?

Establishing Associations

Associations are going to be set by the use of macro like statements that are set before anything else within the model. The great thing about them is that they are very readable to the human eye:

Author model associations

The Author class has many books, and many genres through books

Genre model associations

The Genre class, has many books as well. And, many authors through books.

Book model associations

The Book class, belongs to an author AND belongs to a genre.

Not only are these associations very readable within Ruby. If you look closely, perhaps you already noticed, but the singularization and pluralization within our association coincide perfectly with that they actually are. That is to say, when these associations are being made it is important to ensure that the proper usage is taking place. You’ll see a little later down the road, but not only does it make sense grammatically, it also makes sense to us as the programmer as we begin to use the associations within our app.

Before opening up that can of worms, it’s important to understand the different kinds of associations. There are 6 in total, however I will only be going over 3 in depth. Just because I am lazy though, doesn’t mean that you have to be — documentation on associations is extremely straight forward and informative for anyone looking to expand their understanding of associations with Ruby or Active Record.

1. Belongs to

The belongs_to association is exactly what is says. ‘A Book belongs to an Author.’ Just because the statement is made though doesn’t mean that it’s actually true. Just because you have a Harry Potter book in your hand doesn’t mean that it belongs to J.K. Rowling does it? No, of course not. The world would be in complete anarchy if that’s how we thought of associations. J.K. Rowling has her name printed on each of the books that she wrote. That’s how everyone around the world knows that she is the author, and the book belongs to her. You deciding to pay money to read and keep a copy of it is your business — but it still belongs to her.

In our case, we are going to demonstrate our author-book association using a Foreign-key. What I mean by that is using the unique identifier for an author (it’s ID) within your database, and matching that identifier to an attribute that you have given each book. Here is an example:

Holiday season associations illustration

Inside of our app and database, we have an Author instance for Frosty Snowman. His name is Frosty Snowman, he has 1 book, and his publishing company is ‘Penguin Random House’. When we saved Frosty to our database, sqlite3 was nice enough to assign Frosty an ID of 1 and keep records of all his information.

Now when we enter Frosty’s book into our database and save it, it will also get its own Book ID so that we can identify it. However much like Frosty has attributes for the number of books he has, and his publishing company — his book has an attribute of ‘author_id’. When we give Frosty’s book his ID as it’s author_id, we are establishing the association between them. The foreign key placement is how we establish and determine our associations!!!

2. Has_many

The has_many relationship is again, self explanatory. You might be thinking, where does the foreign key go here? Well, it goes to the model that belongs_to the model that has_many. What if Frosty Snowman wrote another book about being happy? He wouldn’t need the ID of his new book. His happy book would need his ID to be its foreign key, again establishing the relationship between himself and his new book. This pattern will go on within your app and models for each book, and the author that it belongs to.

The same can be said with Genres. Each book is also going to have a genre_id attribute, that will be assigned the ID of the specific genre it belongs to.

This establishes the has_many association by giving multiple books the same author_id or genre_id as foreign keys. As programmers, this opens a world of possibilities to us. Through these associations we are able to access the information of each book that belongs to Frosty, which books belong to a specific genre and the full spectrum of information about each book.

Again, proper documentation goes into this concept much further and will be of help to use a programmer throughout your career. Give it a read to make sure you fully understand the belongs_to and has_many associations properly.

3. has_many :through

This association is a bit special. It is used by programmers to maintain a many to many relationship through a third model. This third model is often referred to as a ‘joiner model’. Let’s visualize for a moment:

has_many :through Association — Ruby on Rails, section 2.4

Here, we can see that appointments belong to both the doctor and the patient. In addition to a doctor and patient having many appointment, they also have many of each other through their appointments.

To the left, we can see the syntax for writing out the has_many :through relationships in our models.

Think about it in terms of actual real life. You are a patient, and you have a doctor. What is your relationship with that doctor? Odds are, you’re not going out to meet with your doctor frequently, you’re not meeting for lunch and I’m certain they aren’t calling you to talk about their day. No offense to you, that would just be illegal.

What relates you to that specific Doctor is your appointment! You have an appointment with your Doctor a 1pm today. He also has an appointment with you at 1pm today.

You and your doctor have a relationship through the appointment that has been set at 1pm today. BUT, you are not his only patient with an appointment today — he has many patients with many appointments. Unfortunately, you also have other appointments with other doctors today.

You have many doctors through your appointments with them and doctors have many patients with their respective appointments. The foreign keys that are given to each individual appointment, each of which correspond to a doctor or a patient, allow you to establish relationships throughout your models and therefore your app.

Other types of associations

  1. has_one
  2. has_one :through
  3. has_and_belongs_to_many

Each of these associations is similar to the ones reviewed previously, however there are a few special instances where these associations are appropriate to use. Once again, proper documentation will give the true explanation as to how they work and the best time to deploy these associations.

Recap

In my opinion, with object oriented programming languages like Ruby, associations are the life blood of any app that you are creating or working on. These associations are the programmers way of illustrating real life relationships.

In my short time with Ruby, Active Record and now Rails, I have personally enjoyed learning associations and the doors they open for a programmer. The ability to have such abstractness and ability right in your finger tips is such an amazing thing. Why is it important though?

Again, going back to representation of real life. These objects that are included within your app each represent something in the real world. Having the ability to say that your tweet belongs to you is extremely important. What if when you tweeted, it was just a tweet. Nobody knew where it came from or who posted it, sounds like a dumpster fire waiting to happen if you ask me.

Resources:

There are many resources for documentation on Active Record Associations, here are a few reliable sources that I use:
- Ruby on Rails
- Ruby on Rails API
- Ruby docs

You might also want to check out query methods (I’ll follow this blog with another on query methods). This is where the real magic happens. You might say that query methods are like your wand, but you have to have the magic behind your wand (associations) before you can cast any spells.

--

--

Jakob Persons

Software Engineer | Full Stack Developer | Soccer Fanatic