2014-09-30 2 views
-3

모든 사용자에 대해 등급이 1-5 인 내 데이터베이스에 users 테이블이 있습니다. 나는 모든 등급에 대해 카운트를 찾고 싶다. 객체로 어떻게 할 수 있습니까?개체 반복 및 해시 결과 가져 오기

사용자 개체가 있습니다.

[#<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 >] 

각 등급 수에 대해 계산하고 싶습니다. 당신이 좋아하면이

counts = User.group(:rating).count 

업데이트

을 시도

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

답변

5

: 평가 1 만 1 수와 등급 5의 2 카운트는 내가 좋아하는 뭔가를 반환하려면이 등급이 제시되지 않으면 0을 반환합니다. Ruby는 많은 방법을 제공합니다. 예를 들어 나는 http://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}을 반환해야합니다. –

+0

답변이 업데이트되었습니다. – gotva

0

기본 Hash 값을 선호 이미 주변의 사용자가있는 경우,이 같은 루비에 약간의 히스토그램을 만들 수있다 :

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

rating_tally(user_array) 

을하지만 당신은하지, 위의 할 경우 @gotva의 SQL 솔루션은 훨씬 빠르고 우아합니다.