2013-03-12 86 views
1

內排序散列我有返回下列陣列的數據模型:紅寶石具有麻煩陣列

[[54993, {:posted_at=>1363066554, :item_id=>55007,..}],..]

54993是POST_ID。我正在嘗試使用這個數組並按posted_at排序。該數組通過posted_at正確排序。這裏是我當前的代碼:

post_ids = UserFeed.new(current_user.id).posts.collect{|x| x[0]} 
    posts = Post.where(:id => post_ids) 

這由post_id,不posted_at進行排序。我試圖弄清楚如何按posted_at排序,並想知道爲什麼數組假設post_id

+0

是這個了activerecord ?無論如何,都要相應地標記它。如果是這樣,我不明白「帖子」關聯如何返回對。在AR中,當關聯配置正確時,您可以編寫'posts = UserFeed.new(current_user.id).posts.order(「posted_at ASC」)' – tokland 2013-03-12 21:56:56

回答

2

where(ids)沒有設置順序,它使用SQL IN (id1, id2, ...)。用ActiveRecord:

post_ids = UserFeed.new(current_user.id).posts.map(&:first) 
posts = Post.where(:id => post_ids).order("posted_at ASC") 

如果沒有屬性posts.posted_at,然後,溶液1:

posts = post_ids.map { |post_id| Post.find(post_id) } 

解決方案2:本執行單個查詢,然後排序:

indexes = Hash[post_ids.map.with_index.to_a] 
posts = Post.where(:id => post_ids).sort_by { |p| indexes[p.id] } 
+0

BOOM!這個答案充滿了勝利。你的第二個建議是正確的。我忘了在問題中提到'posted_at'不是帖子的保存屬性。非常感謝! – jmohsenin 2013-03-12 23:30:01

0

那家真正改變的問題,問題的錯字,使我想到,如果post_ids排序正確的第一件事就是:

posts = [] 

post_ids.each do |post_id| 
    posts << Post.find(post_id) 
end 
+0

對不起,錯字,我的意思是'posted_at',而不是'created_at'。 – jmohsenin 2013-03-12 21:36:24

+0

好吧,這改變了一切.. – Zippie 2013-03-12 21:37:08

+0

此外,這是行不通的,因爲它是一個數組中的散列。 – jmohsenin 2013-03-12 21:38:18

2

如果你真的需要在內存陣列而不是排序使用DB查詢您的數據,試試這個:

method_that_returns_array.sort{ |a, b| a[1][:posted_at] <=> b[1][:posted_at]} 

但與查詢排序的首選方式:

Post.order(:posted_at) 

希望它有幫助:)

+2

更短,更習慣,更快:'method_that_returns_array.sort_by {| x | x [1] [:posted_at]}' – tokland 2013-03-12 22:10:22

+0

感謝您的領導,每天我都會學到新的東西:) – sergelerator 2013-03-12 22:16:40

+0

不客氣:-) http://en.wikipedia.org/wiki/Schwartzian_transform – tokland 2013-03-12 22:18:28