I have a polymorphic association (belongs_to :resource, polymorphic: true
) where resource
can be a variety of different models. To simplify the question assume it can be either a Order
or a Customer
.
If it is a Order
I'd like to preload the order, and preload the Address
. If it is a customer I'd like to preload the Customer
and preload the Location
.
The code using these associations does something like:
<%- @issues.each do |issue| -%>
<%- case issue.resource -%>
<%- when Customer -%>
<%= issue.resource.name %> <%= issue.resource.location.name %>
<%- when Order -%>
<%= issue.resource.number %> <%= issue.resource.address.details %>
<%- end -%>
Currently my preload uses:
@issues.preload(:resource)
However I still see n-plus-one issues for loading the conditional associations:
SELECT "addresses".* WHERE "addresses"."order_id" = ...
SELECT "locations".* WHERE "locations"."customer_id" = ...
...
What's a good way to fix this? Is it possible to manually preload an association?
@issues.preloads(resouce: [:location, :address])
? – BroncobusterActiveRecord::AssociationNotFoundError
. Doesn't look like that'll work (although a syntax like that'd be ideal). – PropitiatoryCONSTRAINT owner_mutex_required CHECK (1 = (license_id IS NOT NULL)::integer + (contract_id IS NOT NULL)::integer + (policy_id IS NOT NULL)::integer)
– Dhahran