Chapter 10. Multiple Table Inheritance
Weâve spent a lot of time on the idea of tweaking your data model
until itâs rock solid, impervious to application-layer bugs or a meddling
Martha at the psql
prompt. By now, you
should feel like youâre ready to practice referential integrity jujitsu or
constraint kung fu. It may come as a surprise, then, to learn that there
is a feature of ActiveRecord, polymorphic
associations, that depends on breaking the
referential integrity weâve worked so hard to ensure.
Before you get your knickers in a knot, remember that ActiveRecord was primarily developed against MySQL, at a time when referential integrity was a âfeatureâ that MySQL did not support. So itâs understandable that some âfeaturesâ crept into ActiveRecord and Rails that are not really features at all but actually disasters waiting to happen.
In this chapter, weâll examine polymorphic associations, understand the problem they were intended to solve, and come up with a better solution that allows us to preserve referential integrity. Weâll continue with our practice of pairing a powerful new pattern at the application layer with getting the most we can for free out of the data layer, allowing the two layers to work together side by side.
The Problem
Polymorphic association allows you to define a relationship between two tables without knowing ahead of time what one of the tables in the relationship is. This allows you to define âxorâ relationships: âA has one of ...
Get Enterprise Rails now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.