Ordering by join table - is this possible?

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.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

^^ I should add

Is it possible to do this in one SQL query?


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs