2014-09-30 67 views
-3

我的數據庫中有一個用戶表,它對每個用戶都有1到5的評分表。我想找到每個評分的計數。我如何用對象來做到這一點?迭代對象,並在散列中獲得結果

我有一個用戶對象。

[#<User id: 1, email: "[email protected]", rating: 1>,#<User id: 2, email: "[email protected]", rating: 3 >,#<User id: 3, email: "[email protected]", rating: 4 >,#<User id: 4, email: "[email protected]", rating: 3 >,#<User id: 5, email: "[email protected]", rating: 4 >,#<User id: 7, email: "[email protected]", rating: 2 >,#<User id: 8, email: "[email protected]", rating: 5 >,#<User id: 9, email: "[email protected]", rating: 5 >] 

我想計算每個評級計數;只有1等級1數和等級5的2計數我想返回類似:

{'1' => 1 ,'2' => 1 ,'3'=>2,'4'=>2,'5'=>2} 

回答

5

試試這個

counts = User.group(:rating).count 

更新

如果你想如果沒有評分,返回0 Ruby提供了很多方法。比如我喜歡默認Hashhttp://apidock.com/ruby/v1_9_3_392/Hash/new/class

result = Hash.new(0) # 0 here is default value 
result.merge!(counts) 

result[2] # some value 
result[-1] # => 0 
+0

我想從1迭代到5,就好像沒有1那樣它應該返回{1 => 0}。 – 2014-09-30 08:14:05

+0

答案已更新 – gotva 2014-09-30 08:23:55

0

如果您已經擁有了用戶身邊,你可以建立在紅寶石這樣的小直方圖:

def rating_tally(users) 
    result = Hash.new(0); 
    users.map(&:rating).each{|k,v| result[k]+=1} 
    result 
end 

rating_tally(user_array) 

但是,如果你不這樣做,上述sql解決方案由@gotva更快,更優雅。