1
ids = [15, 7, 50]
results = Model.where(id: ids)

the results would be model with id 7, 15, 50 in this order, how can i get results by the order of id in ids (15, 7, 50) ?

1

1 Answer 1

1

There're several ways. Easiest database-independent way is to sort in ruby after fetch:

order = ids.each_with_index.to_h
results.sort_by{|item| order[item.id] }

note that that requires fetching whole result into memory and returns an array, which may have some implications depending on your app

In Mysql you can use order by field(id, ...):

Model.where(...).order("field(id, #{ids.join(',')})")`

In postgres 9.5+ - order by array_position(array[...], id):

Model.where(...).order("array_position(array[#{ids.join(',')}], id)")`
3
  • Worth noting that sort_by will return an Array whereas order will return an ActiveRecord::Relation. Dec 7, 2020 at 16:54
  • @muistooshort you're correct, not needed here, array_position is more suitable
    – Vasfed
    Dec 7, 2020 at 17:44
  • I had to encapsulate .order body to Arel.sql(..) otherwise I was getting ActiveRecord::UnknownAttributeReference (Query method called with non-attribute argument(s) error in Rails 6.4.1. Feb 16, 2022 at 15:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.