开发者

ActiveRecord calculating multiple averages

I have a scores table with both score and time per user. I want to calculate both averages grouped by user. I can successfully calculate one of them but not sure how to do both at once.

@scores = SpellingScore.where(:user_id => users).average(:score, :group => :user)

Will produce sql like the following

SELECT AVG(`spelling_scores`.`score`) AS average_score, user_id AS user_id 
FROM `spelling_scores` 
WHERE (`spelling_scores`.`user_id` IN (78767, 78772, 78775)) GROUP BY user_id

I know how to do it in SQL but can't work out the ActiveRecord way.

This is what I want to do...

SELECT AVG(`spelling_scores`.`score`) AS ave开发者_运维百科rage_score, AVG(`spelling_scores`.`time`) AS average_time, user_id AS user_id 
FROM `spelling_scores` 
WHERE (`spelling_scores`.`user_id` IN (78767, 78772, 78775)) GROUP BY user_id

Cheers,

Tim


Thanks for your help Macarthy.

I ended up doing it this way

SpellingScore.select("AVG(`spelling_scores`.`score`) AS average_score, 
AVG(`spelling_scores`.`time`) AS average_time, COUNT(*) AS question_count, user_id AS 
user_id").where(:user_id => users).group(:user_id).includes(:user).order('users.last')

At least I've retained some ActiveRecord chaining.


Just use SQL. Forget the ActiveRecord way, SQL is better for something like this. If you want to keep your logic in your model just create a new method in your model


Wouldn't this work SpellingScore.group(:user).average(:score) Can't test this without a schema though

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜