title: How do you fix the n+1 queries problem in ActiveRecord (Rails 3) when also using the after_initialize callback?
body: <p>Model: </p>
  
  <pre><code>class Project &lt; ActiveRecord::Base
    has_many :user_roles 
    after_initialize :add_user_roles
  
    def add_user_roles
      UserRoles.all.each do |ur|
        self.user_roles &lt;&lt; ur unless self.user_roles.include?(ur)
      end
    end
  end
  </code></pre>
  
  <p>Statement that finds the projects: </p>
  
  <pre><code>@projects = Project.includes(:user_roles)
  </code></pre>
  
  <p>So you can see, I'm telling it to include the user roles association in the query. However, I'm still seeing the n+1 queries problem: it finds the roles once for each project. </p>
  
  <p>If I remove the usage of <code>self.user_roles</code> from the callback and look at the logs, I can see it finds the projects and their user roles in 2 queries - one for the projects, and one for the roles using <code>project_id in (1,2,3,4,5...,n)</code>.</p>
  
  <p>Is there a way to work around this?    </p>
  
  <p>Let me clarify a bit: While I'm willing to work around my specific situation if required, I'd much prefer answers that focused on how to fix the problem in general. I am capable of writing a kludge to get the data in the state that I want it without using the after_initialize callback, and hence not coming into the n+1 queries problem. However, I would rather not do that, so I prefer answers to the general problem as opposed to my specific example.</p>