0

i have a User class which has a column called 'device' of type VARCHAR(255). This column basically contains the device types, for example string 'iPhone 4S', 'iPod Touch 4G', etc...

Is it possible (without loading ALL users and manually doing it) to figure out the total number of occurrences of each device?

So it would return:

iPhone:  50
iPad 2: 54
etc....
4

1 に答える 1

1

これを行うだけです:

counts = User.count(:group => :device)

これは (多かれ少なかれ) 次の SQL に変換されます。

select count(*), device from users group by device

deviceそして、カウントへのハッシュマッピングを取得しますcounts:

{
    'iPhone' => 50,
    'iPad 2' => 54,
    ...
}
于 2012-12-04T03:45:02.177 に答える