On Mar 25, 2009, at 10:46 AM, Neal L wrote:> 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 ;-)
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-xa9cJyRlE0mWcWVYNo9pwxS2lgjeYSpx@public.gmane.org
--~--~---------~--~----~------------~-------~--~----~
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
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---