Jack Christensen
2007-Feb-02 14:02 UTC
How to DRY has_many calculations working with many records
<!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 < ActiveRecord::Base <br> has_many :transactions <br> <br> def balance <br> transactions.sum(:amount) <br> end <br> end <br> <br> class Transaction < ActiveRecord::Base <br> 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 > 100 } <br> <br> A subselect is much faster, but completely duplicates the logic. <br> Person.find(:all, <br> :select => "people.*, (SELECT SUM(amount) FROM transactions WHERE people.id=transactions.person_id) AS balance", <br> :conditions => "(SELECT SUM(amount) FROM transactions WHERE people.id=transactions.person_id) > 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">-- <br> </span>Jack Christensen <br> <a class="moz-txt-link-abbreviated" href="mailto:jackc-/SOt/BrQZzMOf2zXYvRtkodd74u8MsAO@public.gmane.org">jackc-/SOt/BrQZzMOf2zXYvRtkodd74u8MsAO@public.gmane.org</a> <br> <pre class="moz-signature" cols="72">-- Jack Christensen <a class="moz-txt-link-abbreviated" href="mailto:jackc-/SOt/BrQZzMOf2zXYvRtkodd74u8MsAO@public.gmane.org">jackc-/SOt/BrQZzMOf2zXYvRtkodd74u8MsAO@public.gmane.org</a></pre> <br> --~--~---------~--~----~------------~-------~--~----~<br> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. <br> To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org <br> To unsubscribe from this group, send email to rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org <br> For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en <br> -~----------~----~----~----~------~----~------~--~---<br> </body> </html> <br>