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.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 Christensen