Hi Chris,

 I think lazy evaluation is your friend here; I don't know that Rails will
evaluate lazily if you use a find, but if you can reframe that find into a
named scope, you can do this, because named scopes can be composed with
associations and will evaluate lazily.

For example, say your condition was you wanted to find allocations for
payments in the last 24 hours, you could do something like

class Payment
  named_scope(:since, lambda {|time| :conditions => ['payments.created_at >
?', time.getutc]})
end

and then

Payment.since(1.day.ago).allocations.sum(:allocation_amount, :group =>
'accounting_code')


-Kevin

On Fri, May 7, 2010 at 4:02 PM, Chris McCann <[email protected]> wrote:

> This seems like a trivial problem but I'll be darned if I can get it
> to work using ActiveRecord methods.
>
> I have a Payment model which has_many :allocations.  An allocation is
> a portion of the total payment that's tagged for a particular
> purpose.  Each allocation belongs_to an accounting_code for
> bookkeeping purposes.
>
> For example, a payment of $40 could have two allocations, one for $25
> for dues (accounting_code 3) and one for $15 for fees (accounting_code
> 7).
>
> I want to generate an aggregation across a group of payments that
> shows the total allocations to each accounting_code in the group of
> payments like:
>
> 3 : Dues - $150.00
> 7: Fees  - $  60.00
> Total:       $210.00
>
> I can't use this:
>
> payments = Payments.find(....)
> payments.allocations.sum(:allocation_amount, :group =>
> "accounting_code")
>
> because payments is just an array.
>
> Clearly this could be done manually with Ruby by iterating over each
> payment and aggregating the allocation_amounts into a hash with
> accounting_codes as the keys but it sure seems like there should be a
> way to do this with AR.
>
> Can anyone point me in the right direction?
>
> If it can't be done, can a Ruby guru pseudo-code the best way to
> aggregate the allocation amounts by accounting code?
>
> Cheers, and thanks to all of you who contributed to last night's
> meeting!
>
> Chris
>
> --
> SD Ruby mailing list
> [email protected]
> http://groups.google.com/group/sdruby

-- 
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby

Reply via email to