How to eager load a polymorphic model?

瘦欲@ 提交于 2019-12-08 04:43:27

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/11909257/how-to-eager-load-a-polymorphic-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!