Caching a column in a polymorphic relationship
-
24-09-2019 - |
Question
I have content management system application that uses a polymorphic tree table as the core of its arrangement. I've come into a problem where once the tree grows quite large, and because we have quite a few different modules (about 25), just doing :include => :instance doesn't cut the mustard. Instance is the name of our polymorphic relationship.
The funny part is that in most cases when I want a large list of these items, all I really want is their name from the associated table (for the purposes of an index bar for example), all the rest is in the central table. So I thought that I should probably implement some sort of column cache for the name in the central table. (Like a counter cache that rails already does).
I was just wondering if a plugin exists to manage this already?
If not, I was just going to add a 'name' column to the central table and because all the polymorphic models inherit off a superclass, just add a callback that pushes the name across to the central table whenever the item is created or updated. I'd then just do a big migration to populate it in the first place?
Any flaws to that design?
I suppose to be more flexible the column could be some kind of serialised cache where I could store other things later on if need be? Gah! :D
Solution
Well to answer my own question, I added a 'cached_name' column on the central table, created a 'rebuild_cached_name!' method that just went through every record and set the cached name to the proper value. I called the rebuild method from the migration that created the cache column.
I then modified the after_create method on my abstract class (the one that the polymorphs inherit off) and made it assign the cached_name in the central table. I also added an after_update method call that updates the cached_name whenever the normal name is changed.
Pretty simple really, but now it means no longer having to call the polymorphs in simple situations like generating an index bar.