I have a model called User. This users table in the back end has more
than 40 records.
I am trying to extract the TOP 30 records , grouping people by the total
number of residents in each area, ordering them in a descending manner.
The sql query for the same is:-
select area, count(area) as total from users group by area order by
total desc limit 30;
When doing this in Rails, the query looks something like this:-
User.select('area, count(area) as total').group('area').order('total
DESC’).limit(30)
This gives me the areas in descending order, but it doesn’t share the
count in terms of number of residents per area.
I got to know about use of “to_sql” from the active record rails
casts by Ryan B…
When I used the to_sql command in my Rails query, I got:-
User.select('area, count(area) as total').group('area').order('total
DESC’).limit(30).to_sql
SELECT area, count(area) as total FROM `users` GROUP BY area ORDER
BY total DESC LIMIT 30
I got the same sql query as above. But somehow since the count(area)
is not a direct attribute of the Users model, I’m unable to print it
using a Rails query.
I’m able to get the count using User.select('area, count(area) as total').group('area')
,
but this is not giving me the areas in descending order. What it returns
is a hash having the area with the count of number of residents in it.
I’m sure there must be something I’m missing.
Could you please share a work around to this , in case you are aware of
one.
Thanks for your time…