Reputation: 1713
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?
Upvotes: 2
Views: 1874
Reputation: 36860
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)
Upvotes: 5
Reputation: 115521
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 } }
Upvotes: 2