2

I'm using postgres DB & I have an array of product ids: [5, 4, 1, 2] then I invoked

products = Product.where(:id => ids)

Now result products sort after invoking products.map(&:id) is [4, 1, 2, 5]

How can I sort the products using same sort of ids array?

2 Answers 2

5

I'm not in a position to test but this should work...

ids = [5, 4, 1, 2]

products = Product.where(id: ids).order('array_position(?, products.id)', ids)
Sign up to request clarification or add additional context in comments.

3 Comments

nice db implementation, not sure which is best when we only get low number of rows but cool anyway!
corrected answer products = Product.where(id: ids).order("array_position(ARRAY[#{ids.join(',')}], products.id)")
products.id::int. Rails's ids are big int now
2

This would do because you have few rows:

ids = [5, 4, 1, 2] 
products = Product.where(id: ids)
products = ids.map {|id| products.select {|p| p.id == id }  }

2 Comments

@apneadiving thanks but I expect to get ActiveRecord::Relation but this will return an array.
sure thing @SteveTurczyn solution is what you need then :)

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.