title: How to eager load a polymorphic model?
body: <p>I'm trying to optimize some of our queries. One particular challenge was trying to eager load a polymorphic model. In this case, <code>UserView</code> is polymorphic and has the following columns:</p>
  
  <pre><code>user_id, user_viewable_id, user_viewable_type
  </code></pre>
  
  <p>When I try to run this query.</p>
  
  <pre><code>@user_views = UserView.select('user_views.* AS user_views, songs.* AS songs, users.* AS users')
    .joins('INNER JOIN users AS users ON user_views.user_id = users.id')
    .joins('INNER JOIN songs AS songs ON user_views.user_viewable_id = songs.id')
    .where(:user_viewable_type =&gt; 'Song').order('user_views.id DESC').limit(5)
  </code></pre>
  
  <p>It doesn't seem to eager load the query. I am using a gem called <a href="https://github.com/SamSaffron/MiniProfiler" rel="nofollow">MiniProfiler</a>, which indicates that it is actually running n+1 queries, instead of just one.</p>
  
  <p>The following AR query returns this SQL:</p>
  
  <pre><code>SELECT user_views.* AS user_views, songs.* AS songs, users.* AS users FROM "user_views" INNER JOIN users AS users ON user_views.user_id = users.id INNER JOIN songs AS songs ON user_views.user_viewable_id = songs.id WHERE "user_views"."user_viewable_type" = 'Song' ORDER BY user_views.id DESC LIMIT 5
  </code></pre>
  
  <p>Which returns the records all in one query. Strange why this is not working as expected in AR.</p>
  
  <p>Any ideas how to get this to work?</p>