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