Rails 3:选择子模型具有特定条件的所有子模型

发布于 2024-10-19 18:09:37 字数 359 浏览 3 评论 0原文

我的 Rails 数据库方案有项目和任务。我想展示至少有一项未完成任务的项目。这是我的代码:

class Project
    scope :open_tasks, lambda {
        where(:tasks => {:finished => false}).includes(:tasks)
    }
    ...
end

此代码正确返回具有一项开放任务的项目,但仅返回一项开放任务,而不是全部。例如,一个项目总共有 5 个任务和 2 个开放任务,上面的代码将仅返回有 2 个任务的项目。我知道我可以简单地强制重新加载项目,但这非常hackish并且存在性能问题。 我怎样才能获得包含所有任务的项目?

My Rails db scheme has projects and task. I want to show projects which have at least one open task. This is my code:

class Project
    scope :open_tasks, lambda {
        where(:tasks => {:finished => false}).includes(:tasks)
    }
    ...
end

This code correctly returns the projects with one open task, but only with the one open tasks and not all. e.g. a project has 5 tasks total and 2 open task, the code from above would return only the project with 2 tasks. I know that I could simply force to reload the project, but this is very hackish and has performance problems.
How can I get the project with all tasks?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

没企图 2024-10-26 18:09:37

where 条件始终会限制返回哪些关联任务。

听起来您想要返回项目和所有相关任务,无论状态如何,如果这些任务中至少有一项尚未完成?

你可以尝试这个(我认为你不需要 lambda,因为你没有在你的范围内使用任何变量/时间/等)。它假设您有一个 has_many :tasksbelongs_to :project。如果您使用 has_many :through 等,则需要调整它。

scope :open_tasks, where("(select count(*) from tasks where tasks.project_id=projects.id) > 0").includes(:tasks)

The where condition is always going to limit which associated tasks are returned.

It sounds like you want to return the projects and all of their associated tasks regardless of status if at least one of those tasks is not finished?

You could try this (I don't think you need the lambda since you're not using any variables/times/etc. in your scope). It assumes you have a has_many :tasks and belongs_to :project. You'd need to tweak it if you're using a has_many :through, etc.

scope :open_tasks, where("(select count(*) from tasks where tasks.project_id=projects.id) > 0").includes(:tasks)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文