Forum: Ruby on Rails Calculation delegating on Association

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
4daf0b71d5d9a3882e583c0e72eaf5dc?d=identicon&s=25 Alan Francis (Guest)
on 2007-01-19 10:40
Hi,

I'm experiencing a little bit of weird (to me at least) behaviour, and
would appreciate any thoughts...

I have two models, Story and Task.  Story has_many Tasks

I'm building from the ground up test-first, so have been adding
"business logic" type methods to my models.

Story has a method called task_estimate, which is supposed to sum the
estimates on each task to give a total for the story.

Here's the unit test in question:

def test_set_estimate
   assert_equal tasks(:first_task).estimate
stories(:story_with_one_task).task_estimate
   assert_equal 0, stories(:story_with_no_tasks).task_estimate
end

And here's the method I write to pass the test
Here's how I wrote it originally:

def task_estimate
  tasks.sum(:estimate)
end

Now, the first assert passes, so I figure I'm using 'sum' properly.  The
second assert fails saying expected 0, got nil.

I thought I'd found a bug, in summing a collection with no elements, and
right enough there's no test for that in ActiveRecord, but when I do the
following in the console:

Story.create.task_estimate

I get 0 as expected.  So as best I can tell I get nil when summing an
empty association during testing, but not in the console.

As I said above, I'd welcome any thoughts, suggestions, zen-slaps or
other beatings with the "obvious" stick.

A.
C64e63b70be7dfed8b0742540b8b27e5?d=identicon&s=25 Mark Reginald James (Guest)
on 2007-01-20 12:22
(Received via mailing list)
Alan Francis wrote:

> def task_estimate
>  tasks.sum(:estimate)
> end
>
> Now, the first assert passes, so I figure I'm using 'sum' properly.  The
> second assert fails saying expected 0, got nil.

There's definitely a bug in Active Record that causes empty sums
to be returned as nil rather than 0.  The Calculations module casts
the nil result to to the column's type, but this casting always returns
nil for a nil parameter.


> I thought I'd found a bug, in summing a collection with no elements, and
> right enough there's no test for that in ActiveRecord, but when I do the
> following in the console:
>
> Story.create.task_estimate
>
> I get 0 as expected.  So as best I can tell I get nil when summing an
> empty association during testing, but not in the console.

That's strange, I always get nil.

--
We develop, watch us RoR, in numbers too big to ignore.
This topic is locked and can not be replied to.