More concise way to write aggregate query...

Hi all,

Just curious if anyone knows a cleaner way to write this query...

def payments_for(start_on, end_on)     sum = 0     self.leases.each { |lse|         sum += lse.payments.within(start_on, end_on).sum(:amount)     }     sum end

Thanks!

NOTE: This is completely off the top of my head and quite possibly contains bugs :wink:

has_many :leases do    def payments_for(start_on, end_on)      select_value("SELECT SUM(payments.amount) FROM payments INNER JOIN leases ON leases.id = payments.lease_id WHERE #{proxy_owner.class.send(:sanitize_sql, ['payments.paid_on BETWEEN ? AND ? AND leases.some_parent_id = ?', start_on, end_on, proxy_owner.id])}")    end end

Actually, I realize that I'm thinking of 'more performant' rather than 'cleaner' by shifting some work to the database. Since I don't know where the #within method comes from (named_scope perhaps?), I really can't say too much. Your solution is actually quite clean. What prompted you to ask the question?

-Rob

Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com

I was reading about symbol to proc and thought there might be a use here... Yes, within() is a named_scope.

Thanks!