Wrapping Up: Create Polymorphic Associations

Review what we have learned about creating polymorphic associations.

We'll cover the following

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 of Ecto’s tools.

In most cases, we recommend using approach #1 (multiple foreign keys) as it’s the most straightforward approach. However, if the number of foreign keys grows to become problematic, we should consider one of the other two approaches. Which of those two we use is primarily a matter of personal preference. They will both work well—it’s mainly just a matter of which feels more accessible to us.

Ecto’s documentation for belongs_to has a section on polymorphic aassociations and discusses the approaches we covered here. Be sure to check there if you need a refresher on any of these techniques.

Get hands-on with 1400+ tech skills courses.