2010-12-06 129 views
7

我用Ruby工作on Rails的2.3.8,我已經得到了從其他兩個集合構建一個集合排序集合,如下:如何通過created_at屬性

@coll1 = Model1.all 
@coll2 = Model2.all 

@coll = @coll1 << @coll2 

現在,我想喜歡按後代次序按created_at屬性對該集合進行排序。所以,我做了以下:

@sorted_coll = @coll.sort {|a,b| b.created_at <=> a.created_at} 

而且我有以下異常:

undefined method `created_at' for #<Array:0x5c1d440> 

eventhought它存在的那些模型。

請問anyboy能幫我嗎?

+0

如果你選對象的數組,你應該使用`sort_by`,而不是`sort`。有時`sort`會更快,但對象訪問不是其中之一。 – 2010-12-06 21:01:59

回答

21

您共推另一個數組作爲另一個元素融入@coll1數組,你有兩個選擇:

拼合生成的數組:

@coll.flatten! 

或最好只使用+方法:

@coll = @coll1 + @coll2 

而對於分類你應該使用sort_by

@sorted_coll = @coll.sort_by { |obj| obj.created_at } 
2

您的@coll變量中有一個嵌套數組。像這樣:http://codepad.org/jQ9cgpM1

嘗試

@sorted = @coll1 + @coll2 

然後進行排序。

4
@coll1 = Model1.all 
@coll2 = Model2.all 

@coll = @coll1 + @coll2 

@sorted_coll = @coll.sort_by { |a| a.created_at } 
0

由於傑德施耐德表示,解決的辦法是:

@coll1 = Model1.all 
@coll2 = Model2.all 

@coll = @coll1 + @coll2 # use + instead of <<