1

I have an array of IDs:

array_of_ids = [5, 14, 2, 20]

I want to find all records of a class Klass that have an ID in the array, and keep the order they appear in the array.

Klass.where(id: array_of_ids)

returns the correct array, but it is unordered. Is there any way to keep the original order in the array? I can't simply use the order method because it is not an attribute but a method call. I also need to keep it as an active record relation.

max
  • 96,212
  • 14
  • 104
  • 165
Mark
  • 6,112
  • 4
  • 21
  • 46
  • 2
    from this answer https://stackoverflow.com/questions/8322849/mysql-order-by-specific-id-values you could do `Klass.where(id: arr).order("FIELD(id,#{arr.join(',')}")` (if using MySQL) – MrYoshiji Oct 30 '17 at 16:04
  • Postgres? MySQL? – max Oct 30 '17 at 16:04
  • Might help - Postgres - Trying to get the above answer to fit as we speak – Mark Oct 30 '17 at 16:05
  • Thank you - add that as an answer please and I'll accept(I really did google before posting..) – Mark Oct 30 '17 at 16:06
  • 1
    it seems that PostgreSQL offers a similar function called `array_position`: `ORDER BY array_position(ARRAY[3, 1, 2], id);` (seen here: https://gist.github.com/cpjolicoeur/3590737). In your case, a simple `order("array_position(ARRAY[#{ids.join(',')], id)")` should do the trick – MrYoshiji Oct 30 '17 at 16:12
  • wow that seems even easier - am taking a look now thanks... It's amazing how much new information can be gleaned from posts closed by admins... – Mark Oct 30 '17 at 16:18
  • While admin closed, it was a rails question with postgres answers. Had similar problem with sqlite3. `Klass.find([5, 14, 2, 20])` retained the order, where `Klass.where(id:[5, 14, 2, 20])` sorted it by id. On a Postgres application, both seemed to retain the order. Forgot that you can use find with an array of ids. – appleII717 Feb 12 '18 at 16:11

0 Answers0