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
--~--~---------~--~----~------------~-------~--~----~
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 [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---