简体   繁体   English

在Rails中将总和添加到表中的正确方法是什么?

[英]What is the right way to add a sum to a table in Rails?

I'm displaying a list of items which have a price attribute in an HTML table. 我正在HTML表中显示具有price属性的items列表。

What is the right way of getting the total price add the end of the table (and where should the calculation happen)? 什么是获得总正道price添加表(和计算应该在哪里发生)的结束?

I can think of 3 obvious ways, but I don't know which one is the most "orthodoxic" 我可以想到3种明显的方法,但我不知道哪种方法最“正统”

1- in the controller 1-在控制器中

@items = Item.all
@item_total = @items.sum(:price)

and I simply display @item_total in my last line 我只在最后一行显示@item_total

2- in the view, on the last line 2-在视图的最后一行

<%= @items.sum(:price) %>

But I'm not sure that it's OK to do this in a view (it works, but is it OK?) 但是我不确定是否可以在视图中执行此操作(它可以工作,但是可以吗?)

3- in the view, add this on the last line 3-在视图中,在最后一行添加

<%= @items.inject(0){|s, e| s + e.price} %>

But this doesn't feel right to add this kind of logic in the view. 但这在视图中添加这种逻辑是不合适的。

So which one of these is the right one? 那么,其中哪一项是正确的呢? Or is there another way I'm missing? 还是我想念另一种方式?

You should use first option, as view should contain least code. 您应该使用第一个选项,因为视图应包含最少的代码。 Hence use your code in controller only. 因此,仅在控制器中使用您的代码。

@items = Item.all
# this is Array#sum, calculation is done in Ruby. usually slow
@items.sum(:price) 

whereas

# this is Relation#sum -> does a calculation at DB. usually faster
Item.scoped.sum(:price) # OR Item.sum(:price)

It is always desirable to reduce the number of queries that are required to fetch the data from the DB.... You have two options to fetch your data... 总是希望减少从数据库获取数据所需的查询数量。...您有两个选择来获取数据...

@items = Item.all @item_total = @items.sum(:price) @items = Item.all @item_total = @ items.sum(:price)

This would not run as there should be &:price instead of :price...more over if this style of code is now being discouraged due to the non support for the ARel... 这不会运行,因为应该使用&:price而不是:price ...更多,如果由于不支持ARel而现在不鼓励使用这种风格的代码...

Therefore, according to me the code that you should use 因此,根据我的看法,您应该使用的代码

@items = Item.scoped @item_total = @items.pluck(:price).sum(:price) @items = Item.scoped @item_total = @ items.pluck(:price).sum(:price)

The benefit is that the @item is an ARel object and can be used in the further calculations... 好处是@item是ARel对象,可用于进一步的计算...

try this way 尝试这种方式

# In your controller write
@item_total = Item.sum(:price)

and @item_total use in your view file @item_total在您的view文件中使用

Update 更新资料

If you use this like index action then you can do this way 如果您使用类似index操作,则可以这样做

@items = Item.all
@item_total = @items.sum(:price)

but if you want to only item_total then don't pass two queries for sum you can do like 但是,如果您只希望item_total则不要传递两个求和查询,您可以这样做

@item_total = Item.sum(:price)

您可以尝试以下代码:

Sum Dolars: <%= @customer_reports.sum(&:mount) %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM