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?