title: Using scope to calculate SUM from two tables
body: <p>I have two db tables with following fields:</p>
  
  <pre><code>log_lines: id, user_id, date
  fragments: id, log_line_id, amount
  </code></pre>
  
  <p>Corresponding models:</p>
  
  <p><strong>models/log_lines.rb</strong></p>
  
  <pre><code>class LogLine &lt; ActiveRecord::Base
    has_many :fragments, dependent: :destroy
  
    def total_amount
      fragments.sum(:amount)
    end
  end
  </code></pre>
  
  <p><strong>models/fragments.rb</strong></p>
  
  <pre><code>class Fragment &lt; ActiveRecord::Base
    belongs_to :log_line
  end
  </code></pre>
  
  <p>I want to get the amount sum depending user_id. The sql query that does the job:</p>
  
  <blockquote>
    <p>SELECT SUM(f.amount) FROM log_lines AS ll LEFT JOIN fragments AS f ON
    f.log_line_id = ll.id WHERE ll.user_id = 74123;</p>
  </blockquote>
  
  <p>I've created <code>total_amount</code> method in <code>LogLine</code> model and calling it from <code>LogLine</code>
  controller:</p>
  
  <pre><code>amount = 0
  ll_list = LogLine.where(:user_id =&gt; user_id)
  ll_list.each { |ll| amount += ll.total_amount }
  </code></pre>
  
  <p>Actually it works, but I think its not efficient way to implement it. Because many database queries are executed during such collection of data. </p>
  
  <p>Would it be possible to implement this via one <code>scope</code>? </p>