1

I'm trying to optimize some of our queries. One particular challenge was trying to eager load a polymorphic model. In this case, UserView is polymorphic and has the following columns:

user_id, user_viewable_id, user_viewable_type

When I try to run this query.

@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 => 'Song').order('user_views.id DESC').limit(5)

It doesn't seem to eager load the query. I am using a gem called MiniProfiler, which indicates that it is actually running n+1 queries, instead of just one.

The following AR query returns this SQL:

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

Which returns the records all in one query. Strange why this is not working as expected in AR.

Any ideas how to get this to work?

Christian Fazzini
  • 19,613
  • 21
  • 110
  • 215
  • 1
    [Here](http://stackoverflow.com/a/16124295/936494) is a good discussion on this stuff. Hope it helps gain better insights on this issue. – Jignesh Gohel Apr 13 '16 at 10:12

1 Answers1

9

Rails documentation about eager loading says includes works with polymorphic associations. So you should just write:

@user_views = UserView.includes(:user_viewable).
  where(:user_viewable_type => 'Song').order('id DESC').limit(5)
Michaël Witrant
  • 7,525
  • 40
  • 44