4

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 !

  • This is already answered here : https://stackoverflow.com/questions/29096269/rails-activerecord-query-id-in-array-of-ints-keep-order-of-passed-array – Akash Kinwad Feb 07 '22 at 08:58
  • @AkashKinwad the linked question is about Rails 4 which didn't have built-in sorting. – Stefan Feb 07 '22 at 12:09

1 Answers1

7

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

spickermann
  • 100,941
  • 9
  • 101
  • 131
  • 1
    Note: this could be not true in older versions of rails. e.g. rails 4.2.11 `NOTE: The returned records may not be in the same order as the ids you provide since database rows are unordered. You'd need to provide an explicit order option if you want the results are sorted.` – Ursus Feb 07 '22 at 11:20
  • @Ursus That is correct, ancient versions of Ruby on Rails have different behavior. But `find` returns in the described order since Rails 5.2. That means all maintained Rails versions behave like that. And since the OP didn't tag the question with an outdated version number I think it is safe to assume that this stack is not older than 4 years. – spickermann Feb 07 '22 at 11:40
  • it's just a note in case might not work for the op. – Ursus Feb 07 '22 at 11:46
  • 1
    Fair enough! For older versions one would need to pick a work-around from here https://stackoverflow.com/questions/29096269/rails-activerecord-query-id-in-array-of-ints-keep-order-of-passed-array – spickermann Feb 07 '22 at 11:48