如何在Rails中显示列总和

编程入门 行业动态 更新时间:2024-10-27 03:28:20
本文介绍了如何在Rails中显示列总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在我的模型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中显示列总和

本文发布于:2023-10-24 15:01:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524252.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   如何在   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!