title: Most DRY Approach for Rails App with Lots of Subtotaling
body: <p>I have a Rails app that keeps count of User, Comments for many Movie_Categories. The models look like this:</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    has_many :comments
  end
  
  class Movie &lt; ActiveRecord::Base
    belongs_to :movie_category
  
    has_many :comments
  end
  
  class MovieCategory &lt; ActiveRecord::Base
    has_many :movies  
  end
  
  class Comment &lt; ActiveRecord::Base
    belongs_to :movie
    belongs_to :user
  end
  </code></pre>
  
  <p>I can of course find User's Comments count by MovieCategory doing something like this for each MovieCategory:</p>
  
  <pre><code>@user.comment.where("movie_category_id =?", movie_category_id)
  </code></pre>
  
  <p>However, it puts a lot of load on the server, if I need to make this call too frequently, so I was thinking about doing the calculation once per hour (in a background job) for all Users for all Movie_Categories and then storing the counts in the User table, each Movie Category with it's own column.  That way, I don't have to run the calculations for each user as frequently and can just access the counts from the User table.  </p>
  
  <p>The thing I'm wondering is if there is a more dry way to do this since I'm not sure when my Movie_Categories will stop growing (and with each time comes a new table field).  I also thought about caching the User show views (where these counts appear), but even so, if I don't have these columns in the User table then it seems like each time a new User page is loaded (or cached expired) it will have to run through calculating all of this for the User comment counts again.  </p>
  
  <p>Is there a better approach for the issue that I'm facing with not putting too much burden on the server?</p>