Ruby中的Active Record计算

时间:2015-12-30 05:45:11

标签: ruby-on-rails activerecord

有人可以帮助您了解如何在此活动记录条件中使用“where”条件或者为什么会在rails 4.2中抛出错误?

 p = Project.first
  Project Load (34.6ms)  SELECT  `projects`.* FROM `projects`  ORDER BY `projects`.`id` ASC LIMIT 1
 => #<Project id: 1, name: "First Project", created_at: "2015-12-29 16:27:42", updated_at: "2015-12-29 16:27:42"> 

2.2.1 :031 > p.tasks.sum(:priority)
   (26.8ms)  SELECT SUM(`tasks`.`priority`) FROM `tasks` WHERE `tasks`.`project_id` = 1
 => 9 

2.2.1 :032 > p.tasks.sum(:priority).where(:complete => 0)
   (0.2ms)  SELECT SUM(`tasks`.`priority`) FROM `tasks` WHERE `tasks`.`project_id` = 1
**NoMethodError: undefined method `where' for 9:Fixnum**

1 个答案:

答案 0 :(得分:1)

sum返回Fixnum,而非AR关系。您需要撤销wheresum订单:

p.tasks.where(:complete => 0).sum(:priority)