Forum: Ruby on Rails More concise way to write aggregate query...

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Neal L (Guest)
on 2009-03-25 16:47
(Received via mailing list)
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)

Rob B. (Guest)
on 2009-03-25 17:35
(Received via mailing list)
On Mar 25, 2009, at 10:46 AM, Neal L wrote:
>    sum
> end
> Thanks!

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

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.
Neal L (Guest)
on 2009-03-25 21:04
(Received via mailing list)
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. <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.