Rails阵列维护顺序 [英] rails array maintain order
本文介绍了Rails阵列维护顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用硬编码数组
array = [30,29,31,13,10,12,6,7,8,9,11]
尝试执行查询
@pick = Item.where('id IN (?)', array).to_a
所选项目的顺序如何保持初始数组的顺序?
How can the order of Items chosen keep the order of initial array?
推荐答案
假设您要在单个请求中获取所有项目(即无分页),则可以使用初始数组中的索引对获取的项目进行排序,例如
Assuming you're fetching all the items in a single request (i.e. no pagination) then you could sort the items after fetching using the indices from the initial array e.g.
@pick = Item.where('id IN (?)', array).sort_by do |item|
array.index(item.id)
end
这篇关于Rails阵列维护顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文