#14 Performing Calculations on Models
Apr 04, 2007 | 2 minutes | Active Record
Did you know ActiveRecord provides class methods for performing calculations on models? You can even use these methods through associations.
你知道吗?ActiveRecord预制了好多对模型中数据进行统计计算的方法。我们拿Task
类为例。类中有一个标明任务优先级的字段priority
。打开Rails Console,查看操作的回显,其中SQL语句是方法在后台执行的查询。
查询第一个任务的优先级:
terminal
>> Task.first.priority =>4
SQL
SELECT * FROM "tasks" LIMIT 1;
使用预置的统计方法
要是将所有任务的优先级相加呢?(没有实际意义,只是举例子用)
terminal
>> Task.sum(:priority) => 12
SQL
SELECT sum("tasks".priority) AS sum_priority FROM "tasks";
也支持向方法中传递参数:
terminal
>> Task.sum(:priority, :conditions => {:completed => false }) => 2
SQL
SELECT sum("tasks".priority) AS sum_priority FROM "tasks" WHERE (completed="f");
除了sum
,还有minimum
, maximum
和 average
。分别对应最小值,最大值和平均值:
terminal
>> Task.minimum(:priority) => 2
SQL
SELECT min("tasks".priority) AS min_priority FROM "tasks";
terminal
>> Task.maximum(:priority) => 5
SQL
SELECT max("tasks".priority) AS max_priority FROM "tasks";
terminal
>> Task.average(:priority).to_f => 3.0
SQL
SELECT avg("tasks".priority) AS avg_priority FROM "tasks";
使用这些预制的统计方法是通过自动生成的SQL语句,通过数据库完成的计算操作,从效率上要高于把全部要参与计算的对象都读上来,在计算结果。
在级联查询中使用预置统计方法
这些统计方法都是类方法,可以在级联查询中使用。比如说项目类,包含多个任务类Project
,has_many :tasks
)。可以通过如下的方式以某一个项目中的任务为范围进行统计。
terminal
>> project = Project.first => <;Project id: 1, title: "A Project"> >> project.tasks.sum(:priority, :conditions => {:completed => true}) => 10
对应的SQL查询是
SQL
SELECT sum("tasks".priority) AS sum_priority FROM "tasks" WHERE ("tasks"."completed" = 't') AND ("tasks".project_id = 1);