tezvyn:

Polymorphic associations and referential integrity

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

knowing why polymorphic columns break foreign keys.

OUTLINE

a single column can't FK two tables, so integrity is unenforced; alternatives use exclusive arcs or per-type tables.

RED FLAG

claiming a normal FK can target multiple tables.

WHAT THIS TESTS The interviewer wants you to articulate the precise reason polymorphic associations sacrifice database-enforced integrity and to weigh concrete alternatives.

A GOOD ANSWER COVERS In the polymorphic design, commentable_id holds an ID and commentable_type names the table it points to. A foreign key constraint can reference only one table, so the database cannot validate that commentable_id actually exists in the table named by commentable_type. This permits orphaned comments, dangling references after a parent is deleted, no cascade behavior, and validation pushed entirely into application code where bugs leak bad data.

The exclusive-arc alternative gives comments two nullable foreign keys, article_id and video_id, each a real constraint to its table, plus a check constraint ensuring exactly one is non-null. The database now enforces integrity, but you must add a column and constraint per new commentable type. The separate-tables alternative creates ArticleComments and VideoComments, each with a clean foreign key; integrity is perfect, but shared comment logic and a unified feed require unions across tables.

COMMON WRONG ANSWERS Claiming a foreign key can point at multiple tables. Saying application validation is just as safe as a database constraint. Picking an alternative without naming its cost, such as the per-type column sprawl or cross-table unions.

LIKELY FOLLOW-UPS How do you query all comments across types with the exclusive-arc model? How does adding a new commentable type scale in each design? When is the polymorphic trade-off acceptable despite lost integrity?

ONE CONCRETE EXAMPLE With polymorphic columns, deleting an Article leaves comments whose commentable_id now points nowhere, and the database raises no error. With the exclusive-arc design, article_id has ON DELETE CASCADE, so those comments are removed automatically and the constraint guarantees no orphan can ever exist.

Read the original → hashrocket.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.