Approach #1: Multiple Foreign Keys

Learn about implementing polymorphism in Ecto using separate foreign keys.

Before we dive into this approach, let’s remind ourselves of the task. We want to be able to add notes to any artist, album, or track. Each of those records needs to have any number of notes by any number of authors, which is why we elected to store the notes in a separate table rather than add a notes column to each of the three tables.

Add separate foreign keys

One way to achieve this is to have a single notes table, then add separate foreign key columns for each of the tables to which we want to attach notes. Our migration schema definition would look something like this:

Get hands-on with 1200+ tech skills courses.