0

I am trying to show a sum of the floats of all records entered, and I can't seem to figure out how to do it. Here's the situation. My app (purely for learning purposes) has a user who can register a swimmer profile and upon doing so, can record swims for the swimmer. Swim belongs to Swimmer and Swimmer has many swims.

   // swims_controller.rb
   // SwimsController#index
   @swims = @swimmer.swims.all
   @distances = @swimmer.swims.all(:select => "distance")

In the view for this action, I iterate through swims to get swim.date and swim.distance. Then I add this line which doesn't work

<p>Total distance: <%= @distances.each { | x | x.distance.inject(:+).to_f } %></p>

The error I am getting is "undefined method `inject' for 5500.0:Float" (5500.0 is the distance of the first swim recorded for this swimmer). I used inject based on other threads (e.g., How to sum array of numbers in Ruby?) but clearly, I'm missing something. Actually, I'm probably missing quite a lot because I'd like to put this a #total_distance method in the Swim model (swim.rb) but when I try to do that, I can't get the controller to recognize the method and I read elsewhere that a view should not try to access a method defined in a model due to "caching" issues.

Anyone's useful guidance on this would greatly help. Seems like a pretty basic thing to want to do but for some reason, I find scant guidance on a question like this after numerous search queries. Thanks!

Community
  • 1
  • 1
davedub
  • 94
  • 1
  • 8

2 Answers2

1

I am not that experience but try to do <%= @swims.inject(0) {|num,n| num + n[:distance] } %>

OR

<%= @distances.inject {|sum, n| sum + n } %>

I hope this would work.
Thanks.

urjit on rails
  • 1,763
  • 4
  • 19
  • 36
  • Thanks urjit! The first suggestion worked, the second one threw the same error - inject is not a method on float. Now I'm trying to follow how and why it works. swims is the entire array so inject is a method on array, then the function takes num and adds it to the value of the distance (float) attribute. But I don't get how num is identified as a value in the distance column. Can you explain the code a bit further, I'd really like to understand why it works. :) Thanks again! – davedub May 14 '12 at 15:04
0

You should take a look at active record calculation. It already supports sum: http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html

Yuriy Goldshtrakh
  • 2,014
  • 1
  • 11
  • 7