Approach #1: Multiple Foreign Keys
Explore how to implement polymorphic associations in Ecto by adding multiple foreign keys to a single notes table. Understand the advantages, challenges, and best practices, including data integrity and schema validations, enabling you to attach notes to artists, albums, or tracks in Elixir applications.
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:
Our schema definition might ...