Anri
Anri

Reputation: 6265

How to group across 2nd level relations

If database structure is the following:

Projects
Features
- ProjectId FK
Tasks
- FeatureId FK
- Estimate

And models are the following:

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

How do I get a list of tasks for specific project grouped by FeatureId with sum(Estimate) using ActiveRecord query interface?

Upvotes: 0

Views: 39

Answers (3)

Anri
Anri

Reputation: 6265

Did it this way

project = Project.first

Task.where(feature_id: project.features)
    .select("feature_id, sum(estimate)")
    .group("feature_id")

Upvotes: 0

Rafa Paez
Rafa Paez

Reputation: 4860

Try with something like this

Project.joins(:features => :tasks).group("features.id")
 .where("projects.id = ?", project_id).select("tasks.id, SUM(estimate)")

Upvotes: 1

T J
T J

Reputation: 1342

Given a Project object, try

Task.joins(:feature => :project).where(:projects => {:id => project.id}).group("features.id").sum(:estimate)

Upvotes: 1

Related Questions