I added a counter cache called comments_count:
class AddCommentsCountToMicroposts < ActiveRecord::Migration
def change
add_column :microposts, :comments_count, :integer, :default => 0, :null => false
end
end
to basically counts the number of comments for each micropost (Micropost model).
Now, this is how I order microposts by number of comments:
controllers/microposts_controller.rb:
def index
@microposts = Micropost.paginate(:page => params[:page],
:per_page => 5).order('comments_count DESC')
end
(I’m using the will_paginate gem)
Everything works as I want except that it is ordered created_at ASC. When there are two microposts with the same number of comments, the one created earlier is positioned first. I want the opposite, in other words, I want to order by comments_count DESC and created_at DESC at the same time.
Any suggestions to accomplish this?
.order('comments_count DESC, created_at DESC')