title: Get the sum of an associated column in a Rails model
body: <p>My model's set up like so</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    attr_accessible :name
    has_many :predictions
  
  end
  
  class Prediciton &lt; ActiveRecord::Base
    attr_accessible :user_id, :score
    belongs_to :user
  end
  </code></pre>
  
  <p>What I want to do is grab the sum of all the values in the score column for each user.</p>
  
  <p>So far I have come up with this in my view:</p>
  
  <pre><code>&lt;% @user.each do |u| %&gt;
   &lt;% u.predictions.each do |h| %&gt;
    &lt;%= u.name %&gt;&lt;%= h.score %&gt;
  
   &lt;% end %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>but my controller is just </p>
  
  <pre><code>@user = User.all
  </code></pre>
  
  <p>I was thinking something like this may work?</p>
  
  <pre><code>@user = User.all
  @scores = @user.predictions.where("fixture_date &lt;= ?", Date.today).sum(:score)
  </code></pre>
  
  <p>but it doesn't. Am I approaching this the wrong way?</p>