Ordering by join table - is this possible?


#1

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
table?

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.id] = 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
end


#2

^^ I should add

Is it possible to do this in one SQL query?

Thanks