title: Rails 4, Sum value for nested attribute
body: <p>Hello I have nested attribute models like below,</p>
  
  <pre><code>Model Parent
  has_many :students
  has_many :classinos, through: :students
  accepts_nested_attributes_for :students, :reject_if =&gt; lambda { |a| a[:firstname].blank?}, :allow_destroy =&gt; true
  
  Model Student
  belongs_to :Parents, for
  has_many :classinfos, :dependent =&gt; :destroy
  has_many :classlists, :through =&gt; :classinfos
  accepts_nested_attributes_for :classinfos, :reject_if =&gt; lambda { |a| a[:classlist_id].blank?}, :allow_destroy =&gt; true
  
  Model Classinfo
  belongs_to :student, foreign_key: :student_id
  belongs_to :classlist, foreign_key: :classlist_id
  
  Model Classlist
  has_many :students, :through =&gt; :classinfos
  has_many :classinfos
  </code></pre>
  
  <hr>
  
  <p>The relationship is like...
  Parent(calculate tuitions) &lt;&lt; Student &lt;&lt; Classinfo >> Classlist(:tuition)</p>
  
  <p>Model Classlist has a column called "tuition", I want to sum up all the tuition for students and calculate in Parents model.</p>
  
  <p>so far I have...</p>
  
  <pre><code>Model Classinfo
  def tuitioncount
  Classlist.where(:id =&gt; self.classlist_id).sum(:tuition)
  end
  </code></pre>
  
  <p>I can show the tuitioncount for students by</p>
  
  <pre><code>&lt;% @student.classinfos.order(classlist_id: :asc).each do |classinfo| %&gt;
  &lt;%= classinfo.tuitioncount%&gt;
  &lt;%end%&gt;
  </code></pre>
  
  <p>but I dont know how to sum them up and def a method in Model Parent.
  I need something like...</p>
  
  <pre><code>Model Parent
  def balance
  Classlist.where(:id =&gt; self.students.classinfos.classlist_id).sum(:tuition)
  (or)
  Student.where(:member_id =&gt; self.id).sum("student.tuitioncount")
  end
  </code></pre>
  
  <p>Please help me, I don't really know how to extract values from a really far nested model...</p>