Ruby-on-rails Rails 如何对列求和?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8874291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:38:46  来源:igfitidea点击:

Rails how to sum columns?

ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1

提问by Rails beginner

Example I have:

我有的例子:

@test = Pakke.find([[4], [5]])

In my Pakke table I have a column named prismd

在我的 Pakke 表中,我有一列名为 prismd

How do I sum the two values for the prismdcolumns for @test?

如何prismd对@test的列的两个值求和?

回答by Holger Just

You can summarize directly on the database by creating the respective SQL like this:

您可以通过创建相应的 SQL 来直接在数据库上进行汇总,如下所示:

Pakke.sum(:prismd, :conditions => {:id => [4,5]})

See ActiveRecord::Calculationsfor more usage examples and general documentation.

有关更多使用示例和一般文档,请参阅ActiveRecord::Calculations

回答by Jordan Running

ActiveRecord has a bunch of built-in calculation methods, including sum:

ActiveRecord 有一堆内置的计算方法,包括sum

@test = Pakke.where(:id => [4, 5] ).sum(:prismd)

回答by Rails beginner

Pakke.find([[14], [15]]).map(&:prismd).sum

回答by KevinLi

test = Order.where(potential_student_id: potential_student.id).sum("total_price");

test = Order.where(potential_student_id: potential_student.id).sum("total_price");