How to DRY has_many calculations working with many records

class Person < ActiveRecord::Base
 has_many :transactions

 def balance
   transactions.sum(:amount)
 end
end

class Transaction < ActiveRecord::Base
 belongs_to :person
end

Given the above, what is a good way to efficiently and DRYly find people by balance?

Finding all records, then using the association is very slow.
Person.find(:all).select { |p| p.balance > 100 }

A subselect is much faster, but completely duplicates the logic.
Person.find(:all,
 :select => "people.*, (SELECT SUM(amount) FROM transactions WHERE people.id=transactions.person_id) AS balance",
 :conditions => "(SELECT SUM(amount) FROM transactions WHERE people.id=transactions.person_id) > 100"

Especially as the calculations get more complicated this starts to become a real problem.

Thanks.

-- 
Jack C.
[email protected]
--
Jack C.
[email protected]

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [email protected]
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---