0

I want to display the sum of a column name "money" in my model Earning. In the rails console, I can easily get the sum I want Earning.sum(:money) and it shows the sum.

earnings_controller.rb

def index
  @earnings = Earning.sum(:money)
end

index.html.erb

<p id="notice"><%= notice %></p>

<h1>Earnings</h1>

<table>
  <thead>
    <tr>
      <th>Money</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @earnings.each do |earning| %>
      <tr>
        <td><%= earning.money %></td>
        <td><%= link_to 'Show', earning %></td>
        <td><%= link_to 'Edit', edit_earning_path(earning) %></td>
        <td><%= link_to 'Destroy', earning, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Earning', new_earning_path %>

It keeps throwing this error

NoMethodError in Earnings#index

What I've tried so far

I am stumped. I've tried changing the index action to @earnings = earnings.sum(:money) and that gave me this error "NameError in EarningsController#index". I also saw a similar problem here but since I think the issue is in my index.html.erb, it didn't help much. As I said earlier the code works in the Rails Console. Thank you in advance for any help.

bendub89
  • 60
  • 7
  • I have edited for clarity hopefully. So, the problem is me trying to display a sum which occupies 1 field, when my table is trying to display multiple fields? – bendub89 Oct 09 '19 at 18:28

2 Answers2

0

So you are not using @earnings in a proper way, in your view you use earnings as a collecion of objects, but in controller @earnings are defined as a sum of money but you are not using it, if you really need this sum, you can set two instance variables fiest @earnings = Earning.all and the second one @money_sum = Earnings.sum(:money) and then you can display somewhere your sum as = @money_sum, then you can iterate by @earnings to create some linka in your view

DynoMike
  • 49
  • 4
0

It looks like you want to do something like this.

First in your controller you want to get all earnings records.

def index
  @earnings = Earning.all
end

Then in your view you iterate over all @earnings and spit out earnings.money as single value for each of your record.

If you want to get total of all earnings somewhere, you can do @earnings.sum(:money), which will basically give you single value as total of all earnings - Earning.all.

matiss
  • 747
  • 15
  • 36