has_many and sum named_scope

2019-08-24 02:01发布

I have this situation:

Stories has many Tasks
Tasks have an integer called hours_left

I need a named scope to find Stories which all its tasks has more than 0 hours left.

Based on this post. I wrote this:

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

But Story.uncompleted returns an empty array.

Can you help me?

1条回答
三岁会撩人
2楼-- · 2019-08-24 02:25

Solved. That code actually works, the problem is that it returns nil as result of the sum if any of the tasks has hours_left = nil. I validated presence of hours_left and that's all.

查看更多
登录 后发表回答