Find model records by ID in the order the array of IDs were given
        Posted  
        
            by 
                defaye
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by defaye
        
        
        
        Published on 2012-04-14T01:07:10Z
        Indexed on 
            2012/08/28
            9:38 UTC
        
        
        Read the original article
        Hit count: 381
        
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.
© Stack Overflow or respective owner