[英]Sort an active record based on an array of ids
我有一個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的比較失敗
我知道正在進行一些零比較。 如何忽略這一點,還是有更好的方法?
首先根據ID索引的網格關系創建一個哈希,然后根據該索引的查找執行映射:
grid_index = @grid.index_by &:id
@no.map{|id| grid_index[id] } # possibly compact the resulting array after that
發生這種情況是因為@grid
包含了@no
沒有的一些unique_id
。
更換
@grid = Grid.all
用
@grid = Grid.all(:conditions=>["unique_id in (?)",@no])
然后
@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.