How to select database records in an arbitrary order

In Rails, it’s easy to get a bunch of records from your database if you have their IDs:

1 Person.where(id: [1, 2, 3]).map(&:id) = [1, 2, 3]

But what if you wanted to get the records back in a different order? Maybe your search engine returns the most relevant IDs first. How do you keep your records in that order?

You could try where again:

1 Person.where(id: [2, 1, 3]).map(&:id) = [1, 2, 3]

But that doesn’t work at all. So how do you get your records back in the right order?

The compatible...
 •  0 comments  •  flag
Share on Twitter
Published on April 25, 2015 14:01
No comments have been added yet.