Rails阵列维护顺序(rails array maintain order)

3 IT屋

With a hard-coded array

array = [30,29,31,13,10,12,6,7,8,9,11]

trying to execute a query

 @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

使用硬编码数组



  array = [30,29,31,13,10,12,6, 7,8,9,11] 


尝试执行查询



  @pick = Item.where('id IN(?)',array).to_a 


所选项目的顺序如何保持初始数组的顺序?


解决方案

假设您要在单个请求中获取所有项目(即无分页),则可以使用初始数组中的索引对获取的项目进行排序,例如



  @pick = Item.where('id IN(?)',array).sort_by do | item | 
array.index(item.id)
结束

本文地址:IT屋 » Rails阵列维护顺序