ActiveRecord.find(array_of_ids),preserving订单 [英] ActiveRecord.find(array_of_ids), preserving order
问题描述
当你这样做 Something.find(array_of_ids)
Rails中,所得到的数组的顺序并不取决于对 array_of_ids 量级code>。
When you do Something.find(array_of_ids)
in Rails, the order of the resulting array does not depend on the order of array_of_ids
.
有没有办法做到查找和preserve的顺序?
Is there any way to do the find and preserve the order?
ATM我手动排序依据订单ID的记录,但那是一种跛脚。
ATM I manually sort the records based on order of IDs, but that is kind of lame.
UPD:是否有可能使用指定的顺序:为了
参数和某种形式的SQL子句,那么怎么
UPD: if it's possible to specify the order using the :order
param and some kind of SQL clause, then how?
推荐答案
答案是MySQL只
有MySQL中的函数调用 FIELD()
There is a function in mysql called FIELD()
下面是如何,你可以在.find使用它():
Here is how you could use it in .find():
>> ids = [100, 1, 6]
=> [100, 1, 6]
>> WordDocument.find(ids).collect(&:id)
=> [1, 6, 100]
>> WordDocument.find(ids, :order => "field(id, #{ids.join(',')})")
=> [100, 1, 6]
这篇关于ActiveRecord.find(array_of_ids),preserving订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!