I’m not sure what causes the extra ‘to_a’ to get the thing to work,
since invoice_lines.class also returns Array.
invoice_lines.class returns Array, but invoice_lines is not an Array,
but an association proxy.
This association proxy defines a sum (and count etc…) method that is
analogous to the one available on any model.
So in the same way that you would do Invoice.sum(:column_name), you
need to do invoice_lines.sum(:total)
The reason the to_a makes a difference is that it forces the proxy
class to give you the real array.
I’m not sure what causes the extra ‘to_a’ to get the thing to work,
since invoice_lines.class also returns Array.
invoice_lines.class returns Array, but invoice_lines is not an Array,
but an association proxy.
Aha! I see! What I don’t really understand is that invoice_lines.class
is an Array and not something like an ArrayAssociationProxy (or
something along those lines), since (imho) one of Ruby’s awesome
features is duck typing… In this case, it looks like a duck but doesn’t
quack like one.
Another thing I noticed is that sum() on the object requires the name of
a column and not an attribute of the object. I have a case where I want
the sum of a calculated attribute, so I need the to_a in between. I’m
not sure if this is nice behavior.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.