1

我有一个 ActiveRecord @grid。

我有一个哈希@numbers。

导轨控制台

    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 哈希只不过是 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 的比较失败

我知道正在进行一些零比较。如何忽略这一点或有更好的方法?

4

3 回答 3

2

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

grid_index = @grid.index_by &:id
@no.map{|id| grid_index[id] } # possibly compact the resulting array after that
于 2013-03-12T09:33:04.217 回答
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) }
于 2013-03-12T09:32:48.173 回答
0

尝试:

@grid.where(:unique_id => @no).map(&:unique_id)
于 2013-03-12T09:52:40.803 回答