Having polymorphic associations in Rails can be a hard nut to crack. It enforces restriction on joins association which makes it difficult to write complex queries.
Consider following architecture where Defects can be of InspectedTruck or InspectedTrailer associated polymorphically.
Finding defects for inspected trucks using joins will raise error.
We need to write a raw sql INNER JOIN to fetch trucks with defects.
Following query runs perfectly fine.
We faced a scenario in one of our applications with multiple polymorphic joins.
We needed to build a single query which lists vehicle inspection time, truck or trailer number and defect name (if available on the inspected item).
The task here was to query VehicleInspectionReport joining other five different tables and select required attributes to show. But the challenge here was posed by polymorphic association.
We had to come up with a way to query InspectedTruck and InspectedTrailer as a single dataset. We identified the dataset a kind of Single Table Inheritance (STI) dataset. And came up with following subquery.
This subquery gave us all inspected items in a single dataset and we could refer this dataset in a form of STI.
We were then able to build the final query using above subquery.
Add a scope in VehicleInspectionReport to join inspected items.
joins_with_inspected_items scope on VehicleInspectionReport will work in a way of joining a STI table (inspected_items) on VehicleInspectionReport. We can now chain any query which require inspected items. Example:
The underlying concept here is to structure STI dataset from polymorphic architecture. Notice the use of inspected_items dataset in a form of STI using inspected_items.associated_object_id AND inspected_items.associated_object_type.