Difficulty: Advanced
What is a polymorphic association in database design, and what are its problems and alternatives?
A polymorphic association is when one table can belong to rows in several different parent tables through a single relationship, usually stored as a pair of columns like commentable_type and commentable_id. For example, a comments table can point at a posts row or a videos row. It is convenient and popular in ORMs like Rails and Laravel, but the database cannot enforce it with a real foreign key.
The child table holds two columns instead of a normal foreign key:
commentable_type: the name of the parent table or model, such as 'Post' or 'Video'.commentable_id: the primary key value in that parent table.The ORM reads the type column and decides which table to query. Rails calls this belongs_to :commentable, polymorphic: true; Laravel uses morphTo; Django has GenericForeignKey in the contenttypes framework.
FOREIGN KEY must reference exactly one table, so nothing stops commentable_id = 999 pointing at a deleted or non-existent post. Orphans accumulate.ON DELETE CASCADE cannot work, so the application must clean up children, and it often forgets.LEFT JOIN per parent type plus a CASE, or several queries.Post class in code silently breaks every stored row unless you migrate the data.(commentable_type, commentable_id) to be efficient.| Approach | How it works | Trade-off |
|---|---|---|
| Exclusive arc | Nullable post_id and video_id columns plus a CHECK that exactly one is set | Real FKs; add a column per new parent type |
| Separate join tables | post_comments, video_comments each linking to a shared comments table | Clean FKs; more tables |
| Common supertype | A commentable parent table; posts and videos each have a commentable_id FK to it | Proper inheritance; extra insert per parent |
| Separate child tables | post_comments and video_comments with their own columns | Simplest integrity; duplicated structure |
The exclusive arc is the most common upgrade path. In PostgreSQL, CHECK (num_nonnulls(post_id, video_id) = 1) enforces "exactly one parent" neatly.
It is a reasonable choice for low-stakes, append-heavy, cross-cutting data where orphans are harmless: activity feeds, audit logs, tags, likes, notifications. A product like a learning platform might attach "bookmarks" to courses, lessons and articles this way. For anything financial or where deletion must cascade correctly, prefer one of the FK-based designs.
commentable_id, so queries scan every type's rows.CHECK constraint or enum, allowing typos like 'post' vs 'Post'.dependent: :destroy or equivalent.| Polymorphic (type + id) | Exclusive arc | |
|---|---|---|
| Columns on comments | commentable_type, commentable_id | post_id, video_id (nullable) |
| Foreign key enforced | No | Yes, one FK per column |
| ON DELETE CASCADE | Not possible | Works normally |
| New parent type | No schema change | Add a column and update the CHECK |
CREATE TABLE comments (
id BIGSERIAL PRIMARY KEY,
commentable_type TEXT NOT NULL CHECK (commentable_type IN ('Post', 'Video')),
commentable_id BIGINT NOT NULL,
body TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Composite index so lookups by parent are fast
CREATE INDEX comments_parent_idx ON comments (commentable_type, commentable_id);
The CHECK limits valid types, but nothing guarantees commentable_id exists in the matching table.
CREATE TABLE comments (
id BIGSERIAL PRIMARY KEY,
post_id BIGINT REFERENCES posts(id) ON DELETE CASCADE,
video_id BIGINT REFERENCES videos(id) ON DELETE CASCADE,
body TEXT NOT NULL,
-- exactly one parent must be set
CONSTRAINT one_parent CHECK (num_nonnulls(post_id, video_id) = 1)
);
CREATE INDEX ON comments (post_id) WHERE post_id IS NOT NULL;
CREATE INDEX ON comments (video_id) WHERE video_id IS NOT NULL;
Each parent column is a genuine foreign key with cascading delete, and partial indexes keep the indexes small.
Polymorphic Association, Foreign Key, Exclusive Arc, Referential Integrity, ORM