2013-09-27 16 views
0

所以我試圖組合4個不同項目的數組,然後通過列「created_at」對這些數組進行排序,如最新的第一個。因此,結果數組應該是所有這些項目排序的數組,以便最新的項目是第一個,而不管它們是什麼類型。我可以對它進行排序,使最新的項目,但它排序通過每種類型的項目,然後開始排序其他類型。Rails結合了4個數組,並通過「created_at」對結果數組進行排序

例如:類型是襯衫和褲子。我在晚上10點上傳襯衫,然後在晚上10點15分上衣,然後在晚上10點30分再次襯衫。該陣列應該像(襯衫(10:30),褲子(10:15),襯衫(10:00)),而是我得到(襯衫(10:00),襯衫(10:30),褲子(10 :15))

這裏是我的代碼:

@tops = Top.first(15) 
@bottoms = Bottom.first(15) 
@footwears = Footwear.first(15) 
@accs = Accessory.first(15) 

@tempItems = [] 
@temp = [] 
@temp = @tempItems + @tops 
@temp = @temp + @bottoms 
@temp = @temp + @footwears 
@temp = @temp + @accs 

@temp.sort_by{ |temp| - temp.created_at.to_i} 
@itemss = @temp.first(15) 

回答

2

你需要排序的陣列分配回@temp

...

@temp = @temp.sort_by{ |temp| - temp.created_at.to_i} 
+0

謝謝。不知道我是怎麼看不到的。 – nupac

0

您可以通過減少混亂擺脫不必要的分配代碼:

fifteen= [Top, Bottom, FootWear, Accessory]. 
    flat_map{ |c| c.first(15) }. 
    sort_by{ |e| -e.created_at.to_i }. 
    first(15) 
相關問題