Rails 3:选择子模型具有特定条件的所有子模型
我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
where
条件始终会限制返回哪些关联任务。听起来您想要返回项目和所有相关任务,无论状态如何,如果这些任务中至少有一项尚未完成?
你可以尝试这个(我认为你不需要 lambda,因为你没有在你的范围内使用任何变量/时间/等)。它假设您有一个
has_many :tasks
和belongs_to :project
。如果您使用 has_many :through 等,则需要调整它。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
andbelongs_to :project
. You'd need to tweak it if you're using a has_many :through, etc.