has_many 和 sumnamed_scope
我遇到这种情况:
Stories has many Tasks
Tasks have an integer called hours_left
我需要一个命名范围来查找其所有任务剩余时间超过 0 小时的故事。
基于这篇文章。我这样写:
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 返回一个空数组。
你能帮助我吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决了。该代码实际上有效,问题是如果任何任务的 hours_left = nil,它会返回 nil 作为总和结果。我验证了 hours_left 的存在,仅此而已。
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.