has_many 和 sumnamed_scope

发布于 2024-08-06 06:42:28 字数 617 浏览 9 评论 0原文

我遇到这种情况:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鹤仙姿 2024-08-13 06:42:28

解决了。该代码实际上有效,问题是如果任何任务的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文