Ryan Mohr wrote:
If you have a collection of ids, what's the best way to extract the records from the database while maintaining the original id order?
Recently I noticed that a find statement like
% User.find([1, 2, 3])
will return the same thing as
% User.find([3, 2, 1])
...ignoring the order of the ids in the array completely. In my case, I have an array that is twenty ids long and I need the ordering preserved. What's the best solution without having to loop through the ids and select each record one by one? It's a SQL limitation, you can't enforce any order unless you actually use ORDER BY (:order parameter of ActiveRecord::Base.find).
You could create a hash 'id => position' from your original id array and use it to sort the results according to their id.
Lionel