Would something like this suffice?

payments = Payment.all( ... )
Allocation.sum(:allocation_amount,
  :conditions => {:payment_id => payments.map {|p| p.id} },
  :group => 'accounting_code_id')

If the number of payments against which you are filtering is
especially large or you don't need the array of payments for anything
else you may be able to move the conditions used to find the Payments
directly into the call to Allocation.sum, e.g.,

Allocation.sum(:allocation_amount,
  :joins => :payment,
  :conditions => [ "payments..." ],
  :group => 'accounting_code_id')

-John

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
>



-- 
John Parker
[email protected]

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

Reply via email to