Reputation: 3308
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?
Upvotes: 1
Views: 404
Reputation: 8169
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) }
Upvotes: 1
Reputation: 12564
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
Upvotes: 2