title: Adding the sum of a has_many relationship to a model's attributes
body: <p>I have the following (simplified model) and wish to access the 'spent' value in the to_json method of the object, ideally as an attribute of the object. </p>
  
  <pre><code>class Task &lt; ActiveRecord::Base
    has_many    :hours
  
    def spent
      self.hours.sum(:spent)
    end
  end
  </code></pre>
  
  <p>Is there a way to do this without defining a method and hacking the to_json method? I've been hunting for a way to use scope or by hacking the after_initialize method, but none of these methods provide a 'spent' value when using inspect or to_json on the model.</p>
  
  <p>I need to solve this on models higher up the tree that use a has_many, through relationship too.</p>