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.