Denys Medynskyi
Denys Medynskyi

Reputation: 2353

Simple sum not working in Rails

I want to sum columns.

In my controller

         def index
          @performance_reports = PerformanceReport.all
         end

My error:

       undefined method `+' for #<PerformanceReport:0x4a55690>
74:         <td><%=  @performance_reports.sum(:clicks)%></td>

What is wrong ?

Upvotes: 0

Views: 266

Answers (2)

Naveed
Naveed

Reputation: 11167

try

 @performance_reports = PerformanceReport.select('*')

in views

<td><%=  @performance_reports.sum(:clicks)%></td>

basically PerformanceReport.all will load whole table and return Array of PerformanceReport you can't chain queries on Array!!!

PerformanceReport.select('*') will return ActiveRecord::Relation and you can chain any AR method on relation

i suggest you read rails lazing loading strategy Lazy loading (will_paginate sample) and Rails Query Interface

Awesome Rails

Upvotes: 4

davidb
davidb

Reputation: 8954

This sum is an ActiveRecord method so you cant use it on already selected objects! What ypu can do:

PerformanceReport.sum(:clicks)

because then the Database is queried!

Upvotes: 1

Related Questions