Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 652
Florent Guilbaud Avatar asked Sep 16 '25 00:09

Florent Guilbaud


1 Answers

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. [...]

like image 196
spickermann Avatar answered Sep 19 '25 09:09

spickermann