Polymorphic associations in Ruby

Shuyi Yu
3 min readJul 15, 2021

--

Photo by Sharon McCutcheon on Unsplash

What are polymorphic associations?

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. And child model belongs to either one parent model or the other.

For example, we are building a food delivery app. We are going to have 3 USERS types:

  1. Restaurants
  2. Customers (people who want to order food)
  3. Drivers

Each of them has a profile with an address, signup time, etc. Unlike the join table (for example appointment that a doctor and a patient both go to, that both parties share). The profiles table isn’t a join table because one profile only belongs to 1 user instance. It can be a restaurant, can be a customer, can be a driver. But it can’t belong to more than one at the same time.

If we don’t do polymorphic associations, and the profiles table will have many empty values:

If we don’t want to deal with a lot of “nil”s, polymorphic associations in ActiveRecord come in handy.

How to apply?

Instead of asking the child table to have all its parents’ id as its attributes, we simply ask the parents to have the same nickname and inside the child table, add a column to identify who this parent is.

Back to the delivery app example, the child table (profiles) will have a user_id, which equal to the parent’s id, and a user_type to identify who that user_id belongs to. And because the user_id belongs to different parents, there might be the same user_id repeating. And the profiles table looks like the below table:

And when we define their relationship:

Child class: the Profile class belongs_to a parent called user, and we tell have to tell ActiveRecord it is a nickname shared by all the parents, by writing polymorphic: true.

Parent class: parents classes need to tell ActiveRecord they have the nicknames called user by writing in as: :user

Chain it up!

After the polymorphic relationship is established, we can chain it up easily. For example, the Profile class has_many foods. The Driver can access the food (s)he delivered by diver_instance.profile.foods , The customer can access the food (s)he ordered by customer_instance.profile.foods etc.

In the food delivery app example, the relationship between the child and parents is has_one/belongs_to. It also can be has_many/belongs_to in between using polymorphic association as well.

Go explore!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Shuyi Yu
Shuyi Yu

No responses yet

Write a response