1

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

1 Answer 1

1

This should work for you:

list = [3, 1, 2]

Product.where(product_id: list).sort_by { |p| list.find_index(p.product_id) })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.