Wrapping Up
While Ecto doesn’t provide direct support for polymorphic associations as some other frameworks do, it’s still possible to create these associations, thanks to the flexibility that Ecto’s tools provide.
In most cases, we recommend using approach #1 (multiple foreign keys) as it’s the most straightforward approach in most respects. However, if the number of foreign keys grows so large as to become cumbersome, you should definitely consider one of the other two approaches. Which of those two you use is largely a matter of personal preference. They will both work well—it’s largely just a matter of which feels easier to you.
Ecto’s documentation for belongs_to[33] has a section on polymorphic associations and touches on the approaches ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access