2011-08-23 58 views
5

我需要按照傳遞的搜索參數的順序查找記錄。Ruby on Rails:無需排序查找記錄

例如,我有一個字符串:

item_list = "23,12,54,45" 

用下面的查詢,我得到的記錄在 'item_list' 的ASC秩序 - 「12,23,45,54」。

Inventory.find(item_list.split(",")) 

如何修改上面的查詢,使得它在「item_list」的相同順序返回記錄。

謝謝。

+0

什麼已經返回你計劃最大的數據集? – Dex

回答

4

試試這個,雖然它可能只在MySQL工作:

Inventory.where("id IN (#{item_list})").order("find_in_set(id, '#{item_list}')") 

對於較小的數據集,你可以讓紅寶石​​的結果進行排序,但我認爲讓數據庫做的工作對你來說是最好的大套。

0
item_list.split(",").collect do |item| 
    Inventory.find(item) 
end 
+1

不應該收集而是收集每個? –

+0

這將激發許多查詢。 –

+0

@Christopher:它可以;取決於你想要做什麼。在一般情況下,你可能是對的。我現在就改變它。 – jnevelson

0
unordered_records = Inventory.where(:id => item_list) 
item_list.collect { |id| unordered_records.detect { |x| x.id == id } } 
1

請在客戶端這樣的排序:

ids = item_list.split(',') 
items = Inventory.find(ids).sort_by { |i| ids.index(i.id) } 

這隻能使用一個查詢和sort_by只對每個項目,使部分不應該是計算塊一次昂貴。如果你有很多需要處理的項目,那麼你可以輕鬆地構建一個將id映射到其索引的Hash,並在sort_by塊中使用它。

的基本思想是利用排序的另一種結構的一個陣列,例如:

>> a = [ 23, 11, 42, 5 ] 
>> b = [5, 23, 11, 42] 
>> b.sort_by { |i| a.index(i) } 
=> [23, 11, 42, 5]