Approach #1: Multiple Foreign Keys

Before we dive into this approach, let’s remind ourselves of the task at hand. We want to able to add notes to any artist, album, or track. Each of those records needs to be able 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.

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

  create table(​:notes_with_fk_fields​) ​do
  add ​:note​, ​:text​, ​null:​ false
  add ​:author​, ...

Get Programming Ecto now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.