如何跨越二级关系进行分组

时间:2014-02-25 21:59:31

标签: ruby-on-rails group-by rails-activerecord

如果数据库结构如下:

Projects
Features
- ProjectId FK
Tasks
- FeatureId FK
- Estimate

模型如下:

Project has_many features
Feature has_many tasks, belongs_to project
Task belongs_to feature

如何使用ActiveRecord查询界面获取FeatureIdsum(Estimate)分组的特定项目的任务列表?

3 个答案:

答案 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")