Fi3n1k
Fi3n1k

Reputation: 891

Rails - Query table with array of IDs and order based on the array

Let me describe with simple example.

I have a list of numbers:

ex: list = [ 3, 1, 2 ]

and I have a table in DB named Products which have 3 rows with product_id = 1, 2and 3.

Now I need to query Products sort by list values (3,1,2) so the result will be:

product_3 product_1 product_2

Query will be like: product.sort(list) or product.order(list) or some other alternative pls

Upvotes: 1

Views: 77

Answers (1)

jeffdill2
jeffdill2

Reputation: 4114

This should work for you:

list = [3, 1, 2]

Product.where(product_id: list).sort_by { |p| list.find_index(p.product_id) })

Upvotes: 1

Related Questions