2013-05-15 24 views
0

說我有一個用戶模型:導軌 - 如何計算「你打的分數用戶的XX%」

class User < ActiveRecord::Base 

    end 

和答案型號:

class Answer < ActiveRecord::Base 
     belongs_to :user 

    end 

鼓勵用戶發出更多答案,我想向特定用戶展示他/她在所有用戶中的排名。 (排名根據他/她給出的答案數量而定)

我不想因隱私問題創建排名榜。我只想回復一條消息:「你在給出的答案數中擊敗了xx%的用戶」。

我有一個大概的想法,就是做一個組,並得到這個用戶的等級號碼,但我不知道我應該如何使它儘可能高效。

+1

顯示您嘗試過的內容,並且有人可以提出改進建議。雖然這可能更適合codereview.stackexchange.com。 – Barmar

回答

1
class User < ActiveRecord::Base 
    def answered_percentile 
    user_answer_count = answers.count 
    less = User.all.map {|u| u.answers.count}.select {|e| e < user_answer_count}.count 
    100 * less/User.count 
    end 
end 

u = User.find(42) 
puts "you beat #{u.answered_percentile}% of users in the number of answers given out"