简体   繁体   中英

Sort an active record based on an array of ids

I have an ActiveRecord @grid.

I have an 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 is nothing but unique_id => number of clicks

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.

@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

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 :

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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