Refactor Steps
These sections break down the refactoring steps for you.
Refactoring STI
Examine each STI table in your data model. For each, determine how much data is really shared between the subclasses.
If the answer is “not much,” or if different subclasses call for different constraints that are difficult to reconcile with each other, proceed with this multiple table inheritance refactoring.
Create a separate table for each class, custom fit to the class’s needs.
Maintain the inheritance relationship in the model classes, but explicitly use the
set_table_namedirective in each class.In the associated classes, replace built-in association declarations with the MTI-flavored ones developed in this chapter.
Run your tests.
Refactoring: polymorphic => true
Make a list of all the referenced types. You can find this list with the following SQL query, assuming the polymorphic type column is called
{foreign_table}_typeand the association exists in a table calledwidgets:select distinct foreign_table_type from widgets;
For each table referenced, add a column to the table with the polymorphic association (
widgetshere) that references the target table directly. The column should be nullable:alter table widgets add constraint specific_foreign_table_fkey (id) references specific_foreign_table(id);
For each table, set the reference. Keep in mind that your old data may have invalid references, which you should avoid copying:
update widgets set specific_foreign_table_id = foreign_table_id where foreign_table_type ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access