Search code examples
ruby-on-railsruby-on-rails-3activerecord

Find model records by ID in the order the array of IDs were given


I have a query to get the IDs of people in a particular order, say: ids = [1, 3, 5, 9, 6, 2]

I then want to fetch those people by Person.find(ids)

But they are always fetched in numerical order, I know this by performing:

people = Person.find(ids).map(&:id)
 => [1, 2, 3, 5, 6, 9]

How can I run this query so that the order is the same as the order of the ids array?

I made this task more difficult as I wanted to only perform the query to fetch people once, from the IDs given. So, performing multiple queries is out of the question.

I tried something like:

ids.each do |i|
  person = people.where('id = ?', i)

But I don't think this works.


Solution

  • Editor's note:
    As of Rails 5, find returns the records in the same order as the provided IDs (docs).

    Note on this code:

    ids.each do |i|
      person = people.where('id = ?', i)
    

    There are two issues with it:

    First, the #each method returns the array it iterated on, so you'd just get the ids back. What you want is a collect

    Second, the where will return an Arel::Relation object, which in the end will evaluate as an array. So you'd end up with an array of arrays. You could fix two ways.

    The first way would be by flattening:

    ids.collect {|i| Person.where('id => ?', i) }.flatten
    

    Even better version:

    ids.collect {|i| Person.where(:id => i) }.flatten
    

    A second way would by to simply do a find:

    ids.collect {|i| Person.find(i) }
    

    That's nice and simple

    You'll find, however, that these all do a query for each iteration, so not very efficient.

    I like Sergio's solution, but here's another I would have suggested:

    people_by_id = Person.find(ids).index_by(&:id) # Gives you a hash indexed by ID
    ids.collect {|id| people_by_id[id] }
    

    I swear that I remember that ActiveRecord used to do this ID ordering for us. Maybe it went away with Arel ;)