如果数据库结构如下:
Projects
Features
- ProjectId FK
Tasks
- FeatureId FK
- Estimate
模型如下:
Project has_many features
Feature has_many tasks, belongs_to project
Task belongs_to feature
如何使用ActiveRecord查询界面获取FeatureId
与sum(Estimate)
分组的特定项目的任务列表?
答案 0 :(得分:1)
给定Project对象,尝试
Task.joins(:feature => :project).where(:projects => {:id => project.id}).group("features.id").sum(:estimate)
答案 1 :(得分:1)
尝试使用类似的东西
Project.joins(:features => :tasks).group("features.id")
.where("projects.id = ?", project_id).select("tasks.id, SUM(estimate)")
答案 2 :(得分:0)
这样做
project = Project.first
Task.where(feature_id: project.features)
.select("feature_id, sum(estimate)")
.group("feature_id")