How to DRY has_many calculations working with many records

class Person < ActiveRecord::Base
 has_many :transactions

 def balance

class Transaction < ActiveRecord::Base
 belongs_to :person

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.
 :select => "people.*, (SELECT SUM(amount) FROM transactions WHERE AS balance",
 :conditions => "(SELECT SUM(amount) FROM transactions WHERE > 100"

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


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