# Ordering by join table - is this possible?

**URL:** <https://www.ruby-forum.com/t/ordering-by-join-table-is-this-possible/166981>\
**Category:** Rails\
**Created:** [May 1, 2009, 5:56pm UTC](https://www.ruby-forum.com/t/ordering-by-join-table-is-this-possible/166981 "2009-05-01T17:56:31Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dr\_gavin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c37758/32.png) [@dr\_gavin](https://www.ruby-forum.com/u/dr_gavin)\
**Post date:** [May 1, 2009, 5:56pm UTC](https://www.ruby-forum.com/t/ordering-by-join-table-is-this-possible/166981/1 "2009-05-01T17:56:31Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![dr\_gavin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c37758/32.png) [@dr\_gavin](https://www.ruby-forum.com/u/dr_gavin)\
**Post date:** [May 1, 2009, 6:14pm UTC](https://www.ruby-forum.com/t/ordering-by-join-table-is-this-possible/166981/2 "2009-05-01T18:14:06Z")

</div>

^^ I should add

Is it possible to do this in one SQL query?

Thanks
