MID
MID

Reputation: 1825

How to sum object column?

I need to make sum of column.

I think problem is in class, in action where I take performance_reports. I have associsations, so I get all reports related to user by next code:

    @performance_reports = Array.new
     current_user.websites.each do |website|
      reports = website.performance_reports
        reports.each do |report|
        @performance_reports.push(report)
      end
    end

In my view I'm printig each report and in the bottom I want to print summary of column.

Here is view:

   <% @performance_reports.each do |performance_report| %>
      <tr>
        <td><%= performance_report.impressions %></td>
        <td><%= performance_report.clicks %></td>
        <td><%= performance_report.conversions %></td>
      </tr>
     <% end %>
     <tr>
      <td><%=  @performance_reports.count(:clicks)%></td>
      <td><%=  @performance_reports.count(:conversions)%></td>
     </tr>

All - clicls, conversions - are integer type. This code is printing, that summary is 0.

I have two questions: how to sum integers and how to sum not integer columns, which are not saving to database?

Upvotes: 0

Views: 2713

Answers (1)

abhas
abhas

Reputation: 5213

you can use the method sum for this

@performance_reports.sum(:clicks)

it will also sum not integer also as it will return non integer type, to convert it in integer call like this

@performance_reports.sum(:clicks).to_i

Upvotes: 2

Related Questions