title: Eager Load Depending on Type of Association in Ruby on Rails
body: <p>I have a polymorphic association (<code>belongs_to :resource, polymorphic: true</code>) where <code>resource</code> can be a variety of different models. To simplify the question assume it can be either a <code>Order</code> or a <code>Customer</code>. </p>
  
  <p>If it is a <code>Order</code> I'd like to preload the order, and preload the <code>Address</code>. If it is a customer I'd like to preload the <code>Customer</code> and preload the <code>Location</code>. </p>
  
  <p>The code using these associations does something like:</p>
  
  <pre><code>&lt;%- @issues.each do |issue| -%&gt;
  &lt;%- case issue.resource -%&gt;
  &lt;%- when Customer -%&gt;
  &lt;%= issue.resource.name %&gt; &lt;%= issue.resource.location.name %&gt;
  &lt;%- when Order -%&gt;
  &lt;%= issue.resource.number %&gt; &lt;%= issue.resource.address.details %&gt;
  &lt;%- end -%&gt;
  </code></pre>
  
  <p>Currently my preload uses:</p>
  
  <pre><code>@issues.preload(:resource)
  </code></pre>
  
  <p>However I still see n-plus-one issues for loading the conditional associations:</p>
  
  <pre><code>SELECT "addresses".* WHERE "addresses"."order_id" = ...
  SELECT "locations".* WHERE "locations"."customer_id" = ...
  ...
  </code></pre>
  
  <p>What's a good way to fix this? Is it possible to manually preload an association?</p>