title: How to avoid database calls from the View in Rails?
body: <p>Let's assume this example:</p>
  
  <p>Model:</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    has_many :posts
  end
  </code></pre>
  
  <p>Controller:</p>
  
  <pre><code>def index
    @users = User.all
  end
  </code></pre>
  
  <p>View:</p>
  
  <pre><code>&lt;ul&gt;
    &lt;% @users.each do |u| %&gt;
      &lt;li&gt;
        Username: &lt;%= u.username %&gt;&lt;br /&gt;
        &lt;%= pluralize(u.posts.count, "post") %&gt;
      &lt;/li&gt;
    &lt;% end %&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p>From what I understand (by looking at WEBrick in the command line), it does not do a database call for <code>u.username</code>, but it <em>does</em> for <code>u.posts.count</code> for each cycle in the loop. I want to avoid that, so I store the "posts" in an instance variable in the controller (<code>@posts = Post.all</code>, for example) and replace the <code>u.posts.count</code> with <code>@posts.where(:user_id =&gt; u.id).count</code>, but it still does a database call for each cycle. Doesn't the application have all of the information stored in the <code>@posts</code> array in the controller?</p>
  
  <p><em>Note: None of this is specific to my case (I am not displaying a list of users); I'm simply using this to serve as an example.</em></p>