Leonid Shevtsov Leonid Shevtsov - 1 year ago 88
Ruby Question

ActiveRecord.find(array_of_ids), preserving order

When you do

in Rails, the order of the resulting array does not depend on the order of

Is there any way to do the find and preserve the order?

ATM I manually sort the records based on order of IDs, but that is kind of lame.

UPD: if it's possible to specify the order using the
param and some kind of SQL clause, then how?

Answer Source

The answer is for mysql only

There is a function in mysql called FIELD()

Here is how you could use it in .find():

>> ids = [100, 1, 6]
=> [100, 1, 6]

>> WordDocument.find(ids).collect(&:id)
=> [1, 6, 100]

>> WordDocument.find(ids, :order => "field(id, #{ids.join(',')})")
=> [100, 1, 6]