2

I am trying to find the sum of a column called length, which is simple an integer column full of the number of seconds each record lasted for.

I have a search form setup to query the db for some conditions I have set in the controller:

@time_entries = TimeEntry.find(:all, :conditions => [ "(user_id = ?) AND (projecttitle LIKE ?) AND (date BETWEEN ? AND ?)", current_user, '%'+params[:projecttitle]+'%', @startdate, @enddate ])

and then I follow that query with my code that doesn't work, trying to sum the length column of my returned query...

@total_time = @time_entries.sum(:length)

and then when I go to render this out in my view with <%= @total_time %>, I get this error:

undefined method '+' for #<TimeEntry:0x007ffdbbd45b78>

Any ideas? Your help is very appretiated :)

Rob
  • 4,927
  • 12
  • 49
  • 54
briankulp
  • 186
  • 1
  • 11

1 Answers1

4

Change

@total_time = @time_entries.sum(:length)

to

@total_time = @time_entries.sum(&:length)

Just FYI, if you need only one column to operate use :select clause in your query like

@time_entries = TimeEntry.find(:all, :select => 'length', 
                  :conditions => [ "(user_id = ?) AND (projecttitle LIKE ?) 
                           AND (date BETWEEN ? AND ?)", current_user, 
                           '%'+params[:projecttitle]+'%', @startdate, @enddate ])

And if you need only sum of some column from the table you can use sum method like

@total_time = TimeEntry.sum(:length, 
                  :conditions => [ "(user_id = ?) AND (projecttitle LIKE ?) 
                           AND (date BETWEEN ? AND ?)", current_user, 
                           '%'+params[:projecttitle]+'%', @startdate, @enddate ])
Salil
  • 46,566
  • 21
  • 122
  • 156