has_many and sum named_scope

与世无争的帅哥 提交于 2019-12-11 18:33:43

问题


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:


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.



来源:https://stackoverflow.com/questions/1491229/has-many-and-sum-named-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!