title: Is there a a clean way to avoid a double query when testing for an empty ActiveRecord result?
body: <p>In  an .html.erb file, it is quite natural to write something like this:</p>
  
  <pre><code>&lt;% unless @results.empty? %&gt;
    &lt;ul&gt;
      &lt;% @results.each do |result| %&gt;
        &lt;li&gt;
          &lt;%= link_to result.name, '#' %&gt; 
        &lt;/li&gt;
      &lt;% end %&gt;
    &lt;/ul&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>Where @results is the result of an ActiveRecord .all query. Unfortunately this generates two queries to the database: the first looking for a count of the results (the unless condition), the second to retrieve actual results. In this case the query is particularly expensive.</p>
  
  <p>I could simply convert results to an array (which would buffer the entire result set), or put complex logic in the .erb </p>
  
  <p>Neither solution seems to fit the Rails/ActiveRecord design philosophy. </p>
  
  <p>Is there a better way to eliminate the duplicate query? </p>