0

次の 2 つのモデル とCompanyを使用して、次のResponseように企業ごとの合計回答数のクエリを作成しています。

@allResponses = Company.find(current_user_company_id).responses

これにより、次のようなデータが得られます。

[#<Response id: 1, company_id: 1, created_at: "2013-04-24 02:36:54", feedback_score: 10, feedback_explanation: "I really like the way you guys do xyz.", additional_data: "", updated_at: "2013-04-24 02:36:54">, #<Response id: 2, company_id: 1, created_at: "2013-04-25 03:51:07", feedback_score: 5, feedback_explanation: "customer service is spotty.", additional_data: "", updated_at: "2013-04-25 03:51:07">, #<Response id: 3, company_id: 1, created_at: "2013-04-25 03:52:04", feedback_score: 7, feedback_explanation: "You've got potential.", additional_data: "", updated_at: "2013-04-25 03:52:04">, #<Response id: 4, company_id: 1, created_at: "2013-04-25 03:52:18", feedback_score: 9, feedback_explanation: "Almost perfect.", additional_data: "", updated_at: "2013-04-25 03:52:18">] 

このデータから次の 2 つの変数を取得したいと考えています。

@sumOfHighScores = some.thing.here       #sum of feedback_scores that are greater than 8
@sumOfLowScores = some.thing.here.too    #sum of feedback_scores that are less than 7
4

3 に答える 3

2

あなたはこれを試すことができます、

@sumOfHighScores = @allResponses.select{ |response| response.feedback_score > 8 }.map(&:feedback_score).sum
@sumOfLowScores = @allResponses.select{ |response| response.feedback_score < 7 }.map(&:feedback_score).sum
于 2013-04-25T05:50:27.970 に答える
1

データベースですべての計算を実行します。

company = Company.find(current_user_company_id)
totals =  company.responses.sum(
            :feedback_score,
            :group => "CASE WHEN feedback_score < 7 THEN 'low' ELSE 'high' END")
low, high = (totals['low'] || 0), (totals['high'] || 0 )
于 2013-04-25T06:40:41.940 に答える