Florent Guilbaud
Florent Guilbaud

Reputation: 41

keep original array order when appling a active record "where" on it

Just a question, i have an array with some ids array = [19, 5, 1, 4] when i call a where on it Delivery.where(id: array.map(&:id)) to have an active record relation instead an array, the “where” statement is sorting the ids and give me all objects sorting by ids : #<ActiveRecord::Relation [#<Delivery id: 1, ... >, #<Delivery id: 4, ... >, #<Delivery id: 5, ... >, #<Delivery id: 19, ... > Is anyone know how to keep the original order ?

Thanks !

Upvotes: 4

Views: 1981

Answers (1)

spickermann
spickermann

Reputation: 106892

ActiveRecord.find – when called with an array – will return the records in exactly the same order automatically.

Just change your query to:

Delivery.find(array.map(&:id))

Quote from the docs:

NOTE: The returned records are in the same order as the ids you provide. [...]

Upvotes: 9

Related Questions