根据ID数组对活动记录进行排序

时间:2013-03-12 09:05:29

标签: ruby-on-rails arrays sorting activerecord

我有一个ActiveRecord @grid。

我有一个Hash @numbers。

rails console

    1.9.3p385 :086 > Grids
     => Grids(unique_id: integer, price: float, availability: string,
     delivery: string, delivery_time: string, delivery_cost: float, 
     special_offers: text, warranty: text, created_at: datetime, updated_at: datetime) 


    => @numbers
    =>{7=>114, 9=>21, 12=>7, 13=>31, 14=>51, 16=>43, 18=>48, 21=>6, 22=>18, 
       24=>69, 27=>47, 30=>47, 32=>31, 33=>36} 

@numbers hash只不过unique_id =>点击次数

1.9.3p385 :091 > @no =  @numbers.sort_by{|k,v| v}.reverse.map{|i| i[0]} 
              => [7, 24, 14, 18, 30, 27, 16, 33, 13, 32, 9, 22, 12, 21]

@no是unique_id的数组。

@grid = Grid.all

@grid is an activeRecord, I want to sort this active record based 
on the order of @no which is nothing but the unique_id in @grid.

我试着这个,

@grid.sort_by{ |h| @no.index(h.unique_id) }

它没有用,它说,

  

ArgumentError:NilClass与14失败的比较

据我所知,正在进行一些比较。如何忽略这一点还是有更好的方法?

3 个答案:

答案 0 :(得分:2)

首先根据id索引的网格关系创建一个哈希,然后从该索引的查找中执行映射:

grid_index = @grid.index_by &:id
@no.map{|id| grid_index[id] } # possibly compact the resulting array after that

答案 1 :(得分:1)

之所以发生这种情况,是因为@grid包含unique_id所没有的@no

替换

@grid = Grid.all

使用

@grid = Grid.all(:conditions=>["unique_id in (?)",@no])

然后

@grid.sort_by{ |h| @no.index(h.unique_id) }

答案 2 :(得分:0)

尝试:

@grid.where(:unique_id => @no).map(&:unique_id)