问题
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.
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/58310009/how-to-show-sum-of-column-in-rails