Though this doesn't necessarily apply in your instance, one thing to be
aware of when using the "sum" method (which generates a SELECT SUM(field)
... statement) is that you will most certainly run into issues if the
association chain is creating joins.

For example imagine that in your FileRecord model you had a has_many like
this:

has_many :financial_report_lines, :include => :other_things

That include will generate a join in the behind-the-scenes query which has
the potential, to produce multiple "records" for one financial report just
by the mechanics of the join, and those duplicate amounts will be used when
computing the SUM().  ActiveRecord will of course construct everything
properly after the query is run, which is why your in-memory Ruby summation
would still work, but this circumstance makes it entirely possible for the
.sum approach to yield the wrong result.

--
Ben Hughes
Web Application Developer
http://benhugh.es/


On Wed, Feb 24, 2010 at 6:48 PM, Guyren G Howe <[email protected]> wrote:

> I don't have time to dig into why this is happening, since there's an
> obvious workaround, but can anyone quickly tell me why:
>
> >> p.file_record.financial_report_lines.sum('royalty_usd_price').to_f
> => 0.0
>
> but
>
> >>
> p.file_record.financial_report_lines.map(&:royalty_usd_price).inject(&:+).to_f
> => 297.08
>
> (here, royalty_usd_price is a decimal in MySQL).
>
> Regards,
>
> Guyren G Howe
> Relevant Logic LLC
>
> guyren-at-relevantlogic.com ~ http://relevantlogic.com ~ +1 512 784 3178
>
> Ruby/Rails,  REALbasic, PHP programming
> PostgreSQL, MySQL database design and consulting
> Technical writing and training
>
> Read my book, Real OOP with REALbasic: <
> http://relevantlogic.com/oop-book/about-the-oop-book.php>
>
> --
> 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