Moamen Naanou
Moamen Naanou

Reputation: 1713

Sorting ActiveRecord Records by Array

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

Answers (2)

SteveTurczyn
SteveTurczyn

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

apneadiving
apneadiving

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

Related Questions