title: Why isn't this second-level eager loading working?
body: <p>I have three models, Subrating, Thing, and Category. Subrating belongs_to Thing, and Thing has_many Categories.</p>
  
  <p>I have a list of Subratings, and I'm trying to eager-load the Categories that are associated with the Things that are associated with each Subrating.</p>
  
  <p>This is what I tried:</p>
  
  <hr>
  
  <p><strong>controller</strong></p>
  
  <pre><code>@subratings = Subrating.all( :include =&gt; { :thing =&gt; :categories })
  </code></pre>
  
  <p><strong>view</strong></p>
  
  <pre><code>&lt;% @subratings.sort_by(&amp;:rating).reverse.each do |subrating| %&gt;
    &lt;%= subrating.thing.categories.sort_by(&amp;:thing_count).second.name %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <hr>
  
  <p>But it doesn't solve my n+1 problem. I'm not even sure whether the database is lazy-loading Things or Categories or both, but this is the line that keeps reappearing hundreds of times in my server:</p>
  
  <pre><code>CACHE (0.0ms)  SELECT COUNT(*) FROM "things" INNER JOIN "category_things" ON "things"."id" = "category_things"."thing_id" WHERE "category_things"."category_id" = $1  [["category_id", 1]]
  </code></pre>
  
  <p>What am I doing wrong?</p>
  
  <hr>
  
  <p><strong>associations</strong></p>
  
  <pre><code>class Subrating &lt; ActiveRecord::Base
    belongs_to :thing
  end
  
  class Thing &lt; ActiveRecord::Base
    has_many :category_things
    has_many :categories, :through =&gt; :category_things
    has_many :subratings
  end
  
  class Category &lt; ActiveRecord::Base
    has_many :category_things
    has_many :things, :through =&gt; :category_things
  end
  
  class CategoryThing &lt; ActiveRecord::Base
    belongs_to :category
    belongs_to :thing
  end
  </code></pre>