2014-02-25 78 views
0

組如果數據庫結構如下:如何跨越第二級關係

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)

回答

0

嘗試就是這麼做的

project = Project.first 

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

給定一個Project對象,嘗試

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

像這樣的東西

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