I have an array of identifiers stored in some external storage (cache rails or redis). In the controller action, I extract this data and select the object using it, i.e.
ids = [5, 1, 17, 84]
I also want it to be ordered in exactly the same way as the ides in array_of ids:
ids == result.map(&:id) # => true
As a workaround, I use sorting by mysql FIELD function:
MyModel.where(:id => ids).order("FIELD(id, #{ids.join ', '})")
But I do not like this approach, since it is specific to mysql and creates very long queries in the case of a large ids array. Is there a better DB agnostic way to do this? Retrieving unsorted data from the database and sorting on the ruby ββside is undesirable because it is an expensive resource and difficult to use with pagination.
Thank.
sorting ruby-on-rails activerecord
Ineu Dec 14 '11 at 13:13 2011-12-14 13:13
source share