ActiveRecord Includes

断了今生、忘了曾经 提交于 2019-12-11 21:27:43

问题


I have made a workout application with with the following models:

user
routine
lifts
exercises
infos

A routine belongs to a user
A routine has many lifts (which is a joins between exercise and routine)

A lift belongs to an exercise
Infos(sets) belong to a lift

I am digging into ActiveRecord Queries and specifically includes to work on the n+1 problems I am having. When I show the entire routine which shows:

The routines name
The users name
The exercise names for each lift
The sets for each lift

If I want to make less queries can I simply load up everything such as in the following:
a = Routine.includes(:user, :lifts, :exercises, :infos) and loop through all of that to find what I want?

Or do I have to break it down more say:
a = Routine.includes(:user, :lifts)
b = Lift.includes(:exercise, :infos)
in order to shrink the amount of queries I have.

If this question is not clear enough please let me know.


回答1:


Something like the following should work. Routine.includes(:user, {:lifts => [:exercise, :infos]})



来源:https://stackoverflow.com/questions/20108371/activerecord-includes

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