问题描述
假设我有一个非空数组 IDS
的事
对象ID,我想找到对应的对象使用东西= Thing.find_all_by_id(IDS)
。我的IM pression是的东西
不一定有一个排序类似于 IDS
的
-
是我的即时通讯pression是否正确?
-
如果是这样,我可以代替
find_all_by_id
是preserves秩序和不打数据库不必要多少次?
- 是
- 使用阵列#排序
检查出来:
Thing.where(:ID => IDS).sort! {| A,B | ids.index(a.id)< => ids.index(b.id)}
其中(:ID => IDS)
将使用在生成查询()
。然后排序!方法会遍历查询结果,并在IDS阵列比较编号的位置。
Suppose I have a non-empty array ids
of Thing
object ids and I want to find the corresponding objects using things = Thing.find_all_by_id(ids)
. My impression is that things
will not necessarily have an ordering analogous to that of ids
.
Is my impression correct?
If so, what can I used instead of
find_all_by_id
that preserves order and doesn't hit the database unnecessarily many times?
- Yes
- Use Array#sort
Check it out:
Thing.where(:id => ids).sort! {|a, b| ids.index(a.id) <=> ids.index(b.id)}
where(:id => ids)
will generate a query using an IN()
. Then the sort! method will iterate through the query results and compare the positions of the id's in the ids array.
这篇关于是否ActiveRecord的find_all_by_X preserve订单?如果没有,应该用什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!