Introduction to Polymorphic Associations

Learn about creating polymorphic associations.

Add a new feature

Let’s say we wanted to add a new feature to our MusicDB application that would allow us to add notes to our album records. These notes could be anything like metadata about the album (producer, engineer, and so on) or maybe even our comments.

Our first instinct might be to add a “notes” column to the albums table. After some consideration, we would realize that we’d like to allow each record to have multiple notes, perhaps written by different users. So instead of just adding a column, we might decide to create a new notes table and create a has_many/belongs_to relationship between albums and notes. So far, so good.

As we go a little further, we’d like to add notes not just to albums but also to artists and tracks. So we want to keep our notes table, but we want to create associations with more than one table.

Polymorphic associations

This is a case for polymorphic associations. This type of association allows a single record type to have a “belongs to” relationship with more than one type of record. Unlike some database frameworks, Ecto doesn’t have a specific mechanism for managing polymorphic associations. Using some of the tools we’ve already learned about, we can implement the notes feature we’d like to add.

Get hands-on with 1400+ tech skills courses.