← Lessons

quiz vs the machine

Gold1410

Databases

Polymorphic Associations

A foreign key that can point at several tables breaks referential integrity and complicates joins.

5 min read · core · beat Gold to climb

The Pattern

A polymorphic association lets one row reference rows in different tables. A comments table might have a commentable type column saying post or photo, plus a commentable id. The pair identifies which table and which row, so comments attach to many kinds of parent.

Why It Is Used

  • One comments table serves posts, photos, and videos.
  • It feels DRY and is common in ORM frameworks.

The Core Problem

A normal foreign key can only reference one table, so the database cannot enforce that commentable id actually exists. You lose referential integrity: a comment can point at a deleted or nonexistent parent and the database will not stop it.

Better Alternatives

  • Separate columns: a nullable post id and a nullable photo id, each a real foreign key with a check that exactly one is set.
  • Exclusive arc: model each relationship explicitly.
  • Join tables per parent type when relationships are many to many.

These restore real foreign keys and let the database guard integrity.

Key idea

Polymorphic associations let one column target many tables but forfeit referential integrity, so prefer separate real foreign key columns with a check constraint.

Check yourself

Answer to earn rating on the learn ladder.

1. What does a polymorphic association sacrifice?

2. What is a sound alternative to a polymorphic association?