title: Refactoring view loops to use fewer queries via includes with a HABTM relationship
body: <p>I have been trying to refactor this code to reduce the db calls by possibly using "includes". I would like to replace the three nested loops in the view. Tried various options but got stuck... I'm still getting familiar with active record querying.  </p>
  
  <p>How can I make this more efficient with less queries? 
  Is using includes the best option? 
  If so, how do I access the various fields through my HABTM relationships?</p>
  
  <p>Thanks.</p>
  
  <p>Models:</p>
  
  <pre><code>class Category &lt; ActiveRecord::Base
    has_many :pub_types
  end
  
  class PubType &lt; ActiveRecord::Base
    belongs_to :category
    has_and_belongs_to_many :issues
  end
  
  class Issue &lt; ActiveRecord::Base
    has_and_belongs_to_many :pub_types
    has_many :images, :dependent =&gt; :destroy
  end
  </code></pre>
  
  <p>Controller:</p>
  
  <pre><code>def home
    @categories = Category.all
    @issues_and_pubs = Issue.joins(:pub_types).uniq
  end
  </code></pre>
  
  <p>View:</p>
  
  <pre><code>&lt;% @categories.each do |category| %&gt;
      &lt;%= category.name %&gt;
          &lt;% @issues_and_pubs.where(:pub_types =&gt; {:category_id =&gt; ["#{category.id}"]}).each do |issue| %&gt;
              &lt;% issue.images.each do |img| %&gt;
                  &lt;% if img.featured == true %&gt;
                      &lt;%= cl_image_tag img.image, :width =&gt; 295, :height =&gt; 155, :alt =&gt; img.name, :crop =&gt; :fill %&gt;
                      &lt;%= link_to issue.name, issue %&gt;
                  &lt;% end %&gt;
              &lt;% end %&gt;
          &lt;%= issue.issue_date.try(:strftime, "%B %d, %Y") %&gt;
      &lt;%= issue.pub_types.map(&amp;:name).join(", ") %&gt;
      &lt;% end %&gt; 
  &lt;% end %&gt; 
  </code></pre>