问题描述
我想在我的模型Earning中显示列名称 money的总和。
在rails控制台中,我可以轻松获得所需的金额 Earning.sum(:money)
并显示金额。
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 %>
它不断抛出此错误
NoMethodError in Earnings#index
到目前为止我尝试过的事情
我很困惑。我尝试将索引操作更改为@earnings = income.sum(:money),这给了我这个错误 EarningsController#index中的NameError。在,我也看到了类似的问题,但由于我认为问题在我的索引中。 html.erb,它并没有太大帮助。如前所述,该代码可在Rails控制台中使用。
预先感谢您的任何帮助。
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.
推荐答案
因此,您在使用@earnings时并没有正确使用在您的视图中,您将收入用作对象的集合,但在控制器中@earnings被定义为金钱的总和,但您没有使用它,如果您确实需要此总和,则可以设置两个实例变量fiest @earnings = Earning.all第二个是@money_sum = Earnings.sum(:money),然后您可以在某处以= @money_sum的形式显示总和,然后可以通过@earnings进行迭代以在视图中创建一些链接。
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
这篇关于如何在Rails中显示列总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!