views:

147

answers:

2

Hello,

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!

+3  A: 

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}}
Larry K
Exactly what I needed; thanks very much for the quick and accurate response!
David
A: 

ActiveRecord uses the sort order provided by the underlying database, which means you need to provide an "ORDER BY".

To order by ID, you would use

find(:all, :order => "id")
Toby Hede
This isn't exactly what I was looking for. I think it's my fault for not being more clear: the problem is that the IDs aren't always in ascending or descending order. Larry K.'s answers works well for that situation, though.
David