Eager loading and pg_search: good bye to polymorphic association.

August 11, 2014

When we first designed the database schema for our Rails project, we employed the ‘Single Table Inheritance’ and ‘Polymorphic Associations’ strategies to two different and deserving cases. For the latter case, we needed to model different types of a class having common properties as well as unique. So for this, Polymorphic Association was chosen over Single Table Inheritance to achieve a cleaner data structure ( with less holes ).

Since then, the project has evolved and undergone several performance enhancement iterations, and today we decided it was time to lose the polymorphic association at the center of an n + 1 performance problem. With pg_search we were unable to eagerly load to remove some n + 1 DB calls:

The api.rubyonrails.org Rails 4.1.4 explanation: “…the parent model’s type is a column value so its corresponding table name cannot be put in the FROM/JOIN clauses of that query”

Today, the reason for using a Polymorphic Association has all but gone: the unique properties have reduced down to just one integer type column. So we can sidestep this problem, speed up the performance and simplify the project by saying good bye to our polymorphic association.

© 2020 Keith P | Follow on Twitter | Git