Model:
class Project < ActiveRecord::Base has_many :user_roles after_initialize :add_user_roles def add_user_roles UserRoles.all.each do |ur| self.user_roles << ur unless self.user_roles.include?(ur) end end end
Application that finds projects:
@projects = Project.includes(:user_roles)
So you can see, I say, that it includes the association of user roles in the request. However, I still see a problem with n + 1 queries: it finds roles once for each project.
If I remove the use of self.user_roles from the callback and look at the logs, I see that it finds projects and their user roles in two queries - one for projects and one for roles using project_id in (1,2,3,4,5...,n) .
Is there any way around this?
Let me explain a little bit: although I am ready to work on my specific situation, if necessary, I would prefer answers that focused on how to fix the problem as a whole. I can write kludge to get the data in the state that I want, without using the after_initialize callback and therefore without getting into the n + 1 query problem. However, I would prefer not to do this, so I prefer answers to a general problem, as opposed to my specific example.
source share