0
我試圖獲得所有training_stages
的和的days_to_complete
,其中至少有一個training_tasks
和is_complete: => false
。 (請注意,我在名爲Training
的引擎正在處理)ActiveRecord具有子項匹配條件的不同記錄的總和
create_table :training_stages do |t|
t.references :checklist, index: true
t.string :name
t.integer :days_to_complete
t.timestamps
end
create_table :training_tasks do |t|
t.references :stage, index: true
t.string :description
t.boolean :is_public, default: false, null: false
t.boolean :is_complete, default: false, null: false
t.timestamps
end
示例數據
training_stages:
id checklist_id name days_to_complete created_at updated_at
1 1 Intake Stage 8 2014-11-21 21:03:53 2014-11-21 21:03:53
2 1 Document State 6 2014-11-21 21:03:53 2014-11-21 21:03:53
training_tasks:
id stage_id description is_public is_complete created_at updated_at
1 1 Task1 1 0 2014-11-21 21:03:53 2014-11-21 21:03:53
2 1 Task2 0 0 2014-11-21 21:03:53 2014-11-21 21:03:53
3 1 Task3 1 0 2014-11-21 21:03:53 2014-11-21 21:03:53
4 2 Task4 1 0 2014-11-21 21:03:53 2014-11-21 21:03:53
5 2 Task5 0 0 2014-11-21 21:03:53 2014-11-21 21:03:53
6 2 Task6 1 0 2014-11-21 21:03:53 2014-11-21 21:03:53
7 2 Task7 0 0 2014-11-21 21:03:53 2014-11-21 21:03:53
當我運行下面,我得到48
# Assume that stages already contains Stage.all
stages.includes(:tasks)
.where(training_tasks: {is_complete: false})
.sum(:days_to_complete)
它看起來像這樣正在爲每個匹配條件的任務返回一個階段,然後將它們相加。於是我試着分組:
stages.includes(:tasks)
.where(training_tasks: {is_complete: false})
.group("training_stages.id")
.sum(:days_to_complete)
這實際上返回{1=>24, 2=>24}
如何限制總和唯一不同的階段?