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][1] by Ryan Bates. [1]: http://railscasts.com/episodes/202-active-record-queries-in-rails-3 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.. -- Posted via http://www.ruby-forum.com/. -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk@googlegroups.com. To unsubscribe from this group, send email to rubyonrails-talk+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.