使用以下两个模型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">]
我想从这些数据中得到以下两个变量:
@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
答案 0 :(得分: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
答案 1 :(得分:1)
试试这个..
@sumOfHighScores = @allResponses.select{ |response| response.feedback_score > 8 }.sum
@sumOfLowScores = @allResponses.select{ |response| response.feedback_score < 7 }.sum
答案 2 :(得分: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 )