Try to use hash: self.groups.includes(:reports => [:questions, {:user => :image}])
What improvements can be implemented out, with collection and includes in ruby on rails?
-
11-12-2021 - |
Question
I have a very complex query at a beginner level which I am not able to solve out. It takes my page load to around 6 7 seconds on local machine.
The Query is something like for user
self.groups.collect(&:reports).flatten.paginate
Now I run a loop which is something like :
reports.each do |report|
report.name
report.user.name
report.user.image.attachment.url(:thumb) #User has_one :image , Image belongs_to :user
report.questions.each do |question|
question.name
question.answers.each do |answer|
answer.name
end
end
report.comments.each do |comment|
comment.name
comment.user.name
comment.user.image.attachment.url(:thumb) #User has_one :image , Image belongs_to :user
end
end
It has a lot of nested looping which requires a lot of use of includes but me not able to figure out which way should i proceed. My earlier question was N+1 in rails relations with active records?
------------------EDIT------------------
I am able to do
self.groups.includes(:reports => [:user, :questions])
or
self.groups.includes(:reports => [:user => [:image]])
but not
self.groups.includes(:reports => [:user => [:image], :questions])
whats wrong with this ??
------------------EDIT------------------
self.groups.includes(:reports => [:questions, :user => [:image]]).collect(&:reports).flatten.paginate(:page => page, :per_page => 6)
This is what seems to work for me with no extra/less eager loading according to bullet gem( https://github.com/flyerhzm/bullet ) but still it takes some 10 seconds to load up the queries and its like a huge huge load. Any further improvements suggested ??
------------------EDIT------------------
self.groups.includes(:reports => [:questions, .........]).collect(&:reports).paginate
changed to
self.group_reports.includes(:questions, ....... ).paginate
helped a lot
In User Model defined something like
has_many :reports
has_many :group_reports, :through => :groups, :source => :reports
Solution