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

Solution 1:

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 ;)

Solution 2:

As I see it, you can either map the IDs or sort the result. For the latter, there already are solutions, though I find them inefficient.

Mapping the IDs:

ids = [1, 3, 5, 9, 6, 2]
people_in_order = ids.map { |id| Person.find(id) }

Note that this will cause multiple queries to be executed, which is potentially inefficient.

Sorting the result:

ids = [1, 3, 5, 9, 6, 2]
id_indices = Hash[ids.map.with_index { |id,idx| [id,idx] }] # requires ruby 1.8.7+
people_in_order = Person.find(ids).sort_by { |person| id_indices[person.id] }

Or, expanding on Brian Underwoods answer:

ids = [1, 3, 5, 9, 6, 2]
indexed_people = Person.find(ids).index_by(&:id) # I didn't know this method, TIL :)
people_in_order = indexed_people.values_at(*ids)

Hope that helps

Solution 3:

If you have ids array then it is as simple as - Person.where(id: ids).sort_by {|p| ids.index(p.id) } OR

persons = Hash[ Person.where(id: ids).map {|p| [p.id, p] }] ids.map {|i| persons[i] }

Solution 4:

There are two ways to get entries by given an array of ids. If you are working on Rails 4, dynamic method are deprecated, you need to look at the Rails 4 specific solution below.

Solution one:

Person.find([1,2,3,4])

This will raise ActiveRecord::RecordNotFound if no record exists

Solution two [Rails 3 only]:

Person.find_all_by_id([1,2,3,4])

This will not cause exception, simply return empty array if no record matches your query.

Based on your requirement choosing the method you would like to use above, then sorting them by given ids

ids = [1,2,3,4]
people = Person.find_all_by_id(ids)
# alternatively: people = Person.find(ids)
ordered_people = ids.collect {|id| people.detect {|x| x.id == id}}

Solution [Rails 4 only]:

I think Rails 4 offers a better solution.

# without eager loading
Person.where(id: [1,2,3,4]).order('id DESC')

# with eager loading.
# Note that you can not call deprecated `all`
Person.where(id: [1,2,3,4]).order('id DESC').load

Solution 5:

With Rails 5, I've found that this approach works (with postgres, at least), even for scoped queries, useful for working with ElasticSearch:

Person.where(country: "France").find([3, 2, 1]).map(&:id)
=> [3, 2, 1]

Note that using where instead of find does not preserve the order.

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