Skip to content

ActiveRecord: Query Database by Multiple IDs and Keep the Order

Published: at 05:31 PM

Query database by multiple ids - keep the order of ids

ids = [5, 2, 3, 1]

Listing
  .where(id: ids)
  .order("FIELD(id, #{ids.join(',')})")

MySQL version:

SELECT * FROM listings
WHERE id IN (5, 2, 3, 1)
ORDER BY FIELD(id, 5, 2, 3, 1)