简体   繁体   English

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

[英]Sort an active record based on an array of ids

I have an ActiveRecord @grid. 我有一个ActiveRecord @grid。

I have an Hash @numbers. 我有一个哈希@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 is nothing but unique_id => number of clicks @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 is an array of unique_id. @no是unique_id的数组。

@grid = Grid.all @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.

Im trying this, 我正在尝试这个

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

It's not working, it says, 它说,它不起作用,

ArgumentError: comparison of NilClass with 14 failed ArgumentError:NilClass与14的比较失败

I understand there is some nil comparison going on. 我知道正在进行一些零比较。 How to ignore this or is there a better approach? 如何忽略这一点,还是有更好的方法?

first create a hash from your grid relation indexed by id, and then perform a mapping from lookups on this index : 首先根据ID索引的网格关系创建一个哈希,然后根据该索引的查找执行映射:

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

It happens because @grid includes some unique_id which @no does not have. 发生这种情况是因为@grid包含了@no没有的一些unique_id

Replace 更换

@grid = Grid.all

With

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

Then 然后

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

尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM