RailsCasts中文版,#14 Performing Calculations on Models 利用模型自带的统计功能
你知道吗?ActiveRecord预制了好多对模型中数据进行统计计算的方法。我们拿Task
类为例。类中有一个标明任务优先级的字段priority
。打开Rails Console,查看操作的回显,其中SQL语句是方法在后台执行的查询。
查询第一个任务的优先级:
>> Task.first.priority =>4
对应的SQL查询是
SELECT * FROM "tasks" LIMIT 1;
使用预置的统计方法
要是将所有任务的优先级相加呢?(不一定有实际意义,只是举例子用)
>> Task.sum(:priority) => 12
对应的SQL查询是
SELECT sum("tasks".priority) AS sum_priority FROM "tasks";
也支持向方法中传递参数:
>> Task.sum(:priority, :conditions => {:completed => false }) => 2
对应的SQL查询是
SELECT sum("tasks".priority) AS sum_priority FROM "tasks" WHERE (completed="f");
除了sum
,还有minimum
, maximum
和 average
。分别对应最小值,最大值和平均值:
>> Task.minimum(:priority) => 2 >> Task.maximum(:priority) => 5 >> Task.average(:priority).to_f => 3.0
SELECT min("tasks".priority) AS min_priority FROM "tasks"; SELECT max("tasks".priority) AS max_priority FROM "tasks"; 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);
作者授权:Your welcome to post the translated text on your blog as well if the episode is free(not Pro). I just ask that you post a link back to the original episode on railscasts.com.
原文链接:http://railscasts.com/episodes/14-performing-calculations-on-models