Rails activerecord where in 以特定顺序获取结果

Rails activerecord where in get results in specific order

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

结果将是 id 为 7、15、50 的模型,如何按 ids (15、7、50) 中的 id 顺序获得结果?

有几种方法。 最简单的独立于数据库的方法是在获取后在 ruby 中排序:

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

请注意,这需要将整个结果提取到内存中并 returns 一个数组,这可能会产生一些影响,具体取决于您的应用程序

在Mysql中你可以使用order by field(id, ...):

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

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

Model.where(...).order("array_position(array[#{ids.join(',')}], id)")`