has_many和sum named_scope

时间:2009-09-29 08:21:05

标签: activerecord group-by sum join named-scope

我遇到这种情况:

Stories has many Tasks
Tasks have an integer called hours_left

我需要一个命名范围来查找所有任务剩余时间超过0小时的故事

基于this post。我写了这个:

class Story
  has_many :tasks
  named_scope :uncompleted, { 
    :joins=>["INNER JOIN tasks ON tasks.story_id = stories.id"],
    :group=> 'stories.id',
    :select=>'stories.*, SUM(tasks.hours_left) AS sum_amount',
    :having=>"sum_amount > 0"
  }
end

但是Story.uncompleted返回一个空数组。

你能帮助我吗?

1 个答案:

答案 0 :(得分:0)

解决。该代码实际上有效,问题是如果任何任务有hours_left = nil,则返回nil作为总和的结果。我验证了hours_left的存在,这就是全部。