Your data structure to store the ranking/order could be improved. Something like,
{ record_id => order }
You can generate 1 by doing this
sorted_hash = hash.sort { |a, b| a.first <=> b.first }.each_with_object({}) { |a, m| m[a.last] = a.first }
ar_collection
is your ActiveRecord collection.
ar_collection.sort { |a, b| sorted_hash[a.id] <=> sorted_hash[b.id] }
Your hash might be missing some data, ex. record id: 100, is not part of the hash.
So you can avoid the exception as such:
ar_collection.sort { |a, b| sorted_hash[a.id] || 0 <=> sorted_hash[b.id] || 0 }
The missing ranking, will be at the top.