title: Rails calculate averages
body: <p>I have a rake task in which I am calculating the average for a set of products, however I am having trouble calculating and updating the attributes for <strong>individual</strong> each set. What I have so far:</p>
  
  <pre><code>task :calculate_rating =&gt; :environment do 
  total_rating = []
    Product.find(:all, :joins =&gt; :rating_sets, :conditions =&gt; ["rating_set_id = ?", 45 ]).each do |product|
    Rating.find(:all, :conditions =&gt; ["rating_set = ? and product_id =?", 45 ,product.id]).each do |ratings|
      total_rating &lt;&lt; ratings.rating
          end
        average = total_rating.inject(:+).to_f / total_rating.size
        q = ProductRatingSet.find_by_product_id_and_rating_set_id(@product_id, 45)
        q.update_attribute(:product_rating, average)
          end
        end
  </code></pre>
  
  <p>Im trying to basically find the average and update the <code>product_rating</code> for each set that is retrieved by <code>Rating.find(:all, :conditions =&gt; ["rating_set = ? and product_id =?", 45 ,product.id])</code>. </p>