You have to order on count AND another column (id
would be the best), in this way SQL will returns a list that will not change (because right now SQL does not know what to do if X records have the same count).
You can change .order(sort_column)
to .order("#{sort_column} ASC, id ASC")
, and it should work.