fcastillo
fcastillo

Reputation: 948

Get elements by id array and order by this array

I want te get, for example, products by id array but I want these products on same order that id array.

For example, I want products with id 6, 3, 8:

ids = [6, 3, 8]
Product.where(id: ids)

It gives me products but the first is product with id = 3, second with id = 6...

And I want these products in same order that ids array. I want the first product with id = 6, the second with id = 3...

How could I do that in Products query?

Upvotes: 3

Views: 601

Answers (2)

Ilya
Ilya

Reputation: 13487

Indexing should work:

Product.where(id: ids).index_by(&:id).values_at(*ids)

Or just (checked in MySQL, but sanitize ids before if ids are coming from external source):

Product.where(id: ids).order("field(id, #{ids.join(', ')})")

Upvotes: 3

potashin
potashin

Reputation: 44601

If you want to do this in one ActiveRecord query, it depends on the RDBMS you are using and will include a raw sql string in the order method, but you can also do this in plain ruby:

Product.where(id: ids).sort_by { |item| ids.index(item.id) }

P.S. After sorting class of the collection is going to change from ActiveRecord_Relation to Array.

Upvotes: 2

Related Questions