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)


On Mar 25, 2009, at 10:46 AM, Neal L wrote:



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 = payments.lease_id WHERE
#{proxy_owner.class.send(:sanitize_sql, [‘payments.paid_on BETWEEN ?
AND ? AND leases.some_parent_id = ?’, start_on, end_on,])}”)

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 B.
[email protected]

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


On Mar 25, 10:35 am, Rob B. [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs