Forum: Ruby on Rails How to DRY has_many calculations working with many records

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
89441a6c74647d292f5cc951eae24cfa?d=identicon&s=25 Jack Christensen (Guest)
on 2007-02-02 15:03
(Received via mailing list)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <meta content="text/html;charset=ISO-8859-1"
http-equiv="Content-Type">
  <title></title>
</head>
<body bgcolor="#ffffff" text="#000000">
class Person &lt; ActiveRecord::Base
<br>
&nbsp;has_many :transactions
<br>
<br>
&nbsp;def balance
<br>
&nbsp;&nbsp; transactions.sum(:amount)
<br>
&nbsp;end
<br>
end
<br>
<br>
class Transaction &lt; ActiveRecord::Base
<br>
&nbsp;belongs_to :person
<br>
end
<br>
<br>
Given the above, what is a good way to efficiently and DRYly find
people by balance?
<br>
<br>
Finding all records, then using the association is very slow.
<br>
Person.find(:all).select { <code class="moz-txt-verticalline"><span
 class="moz-txt-tag">|</span>p<span class="moz-txt-tag">|</span></code>
p.balance &gt; 100 }
<br>
<br>
A subselect is much faster, but completely duplicates the logic.
<br>
Person.find(:all,
<br>
&nbsp;:select =&gt; "people.*, (SELECT SUM(amount) FROM transactions
WHERE
people.id=transactions.person_id) AS balance",
<br>
&nbsp;:conditions =&gt; "(SELECT SUM(amount) FROM transactions WHERE
people.id=transactions.person_id) &gt; 100"
<br>
<br>
Especially as the calculations get more complicated this starts to
become a real problem.
<br>
<br>
Thanks.
<br>
<br>
<span class="moz-txt-tag">--&nbsp;<br>
</span>Jack Christensen
<br>
<a class="moz-txt-link-abbreviated"
 href="mailto:jackc@hylesanderson.edu">jackc@hylesanderson.edu</a>
<br>
<pre class="moz-signature" cols="72">--
Jack Christensen
<a class="moz-txt-link-abbreviated"
href="mailto:jackc@hylesanderson.edu">jackc@hylesanderson.edu</a></pre>
<br>
--~--~---------~--~----~------------~-------~--~----~<br>
You received this message because you are subscribed to the Google
Groups &quot;Ruby on Rails: Talk&quot; group. <br> To post to this
group, send email to rubyonrails-talk@googlegroups.com <br> To
unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe@googlegroups.com <br> For more options,
visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en <br>
-~----------~----~----~----~------~----~------~--~---<br>
</body>
</html>
<br>
This topic is locked and can not be replied to.