Improve ActiveStorageLoader example for STI models #170
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Update ActiveStorageLoader to Support STI Models
Description:
This pull request updates the ActiveStorageLoader example to make it smarter so that it better supports Single Table Inheritance (STI) models.
Long context:
Previously, the ActiveStorageLoader class assumed that the
record_type
(the model that has the attachment) was always the class where thehas_one_attached
orhas_many_attached
was defined. However, in an STI setup, the attachment could be defined on any of the ancestor classes of the model, not just the model itself.For example, consider the following STI setup:
In this case, both
Car
andTruck
models inherit the document attachment from the Vehicle parent class. If we were to use theActiveStorageLoader
withrecord_type
set to"Car"
or"Truck"
, it would not find the attachment, because it's defined on theVehicle
parent class, so therecord_type
is actually"Vehicle"
.The following would NOT load the attachment:
In plain sight this might seem easily avoidable by simply calling the
ActiveStorageLoader
withVehicle
. However, there are times where we call the loader dynamically from a more complex context so it's better to make theActiveStorageLoader
so that it can be called with a subclass and it would still find the attachment.For instance, you might have an extension to load the attachment blob url:
Solution
To address this, this PR updates the ActiveStorageLoader class to get all ancestor classes of
record_type
that are descendants ofActiveRecord::Base
. This ensures that we correctly handle attachments for all possiblerecord_types
, whether it's the model itself or any of its ancestors in the STI hierarchy.