Forum: Ruby on Rails ordering by join table - is this possible?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Gavin M. (Guest)
on 2009-05-01 19:56
(Received via mailing list)
Hey all

Suppose Post has many comments.

Is it possible to call Post.all and order them by the number of
comments each has without adding a column 'comments_count' to the Post

If not, can anyone think of a nicer way of doing it this than:

def Post.order_by_comments
  posts = Post.all
  post_hash = {}
  posts.each { |post| post_hash[] = post.comments.count }
  sorted_posts = posts.sort {|a,b| a[1]<=>b[1] }  # =>sorts by keys
  ids = sorted_posts.collect(&:first)  # => collects the post ids
  ids.reverse! # =>sorts the ids from most comments to least
Gavin M. (Guest)
on 2009-05-01 20:14
(Received via mailing list)
^^ I should add

Is it possible to do this in one SQL query?

This topic is locked and can not be replied to.