Rails/ActiveRecord: Return order with ActiveRecord#find(Array)

activerecordruby-on-rails

I'm using Ruby on Rails/ActiveRecord and am having trouble with an ActiveRecord#find call. I'm storing in the database a serialized array of recently viewed documents IDs. The IDs are stored in descending order of when they were last viewed, so the most recently viewed document ID is first in the array. The array includes 10 IDs maximum.

So far, so good. The problem is that ActiveRecord#find(Array) seems to ignore the order in which the ideas appear in the array. So if I type Document.find([1, 2, 3]), I get the same result as if I do Document.find([3, 2, 1]).

My question, then, is this: how can I get an ActiveRecord result array that is in the same order as the IDs I passed to #find? Or, if ActiveRecord doesn't make this possible directly, how can I sort the resulting Array after the fact?

Thanks so much for any answers people can contribute!

Best Answer

ActiveRecord is an interface to your database and returns the records to you in the same order that the database returns them. If you don't supply an 'order' parameter then the returned order is (effectively) random.

If your order is by id ascending or descending:

results = SomeModelName.find([1,2,3], :order => "id") # ascending order
results = SomeModelName.find([1,2,3], :order => "id desc") # descending order

If id order is not ascending or descending:

ids = [1, 3, 2]
r = SomeModelName.find(ids)
results = ids.map{|id| r.detect{|each| each.id == id}}