O'Reilly logo

Enterprise Rails by Dan Chak

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 B or C but not both.” Usually, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required