How to sort a collection by the created_at attribute

I am working with Ruby on Rails 2.3.8, and I have a collection that is built from two other collections:

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

Now I would like to sort this collection using the created_at attribute in the descendant stream. So, I did the following:

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

And I have the following exception:

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

eventhought exists for these models.

Can anyone help me out?

+7
ruby ruby-on-rails
source share
4 answers

You clicked another array as another element into the @coll1 , you have two options:

Smooth the resulting array:

 @coll.flatten! 

Or just use the + method:

 @coll = @coll1 + @coll2 

And for sorting you should use sort_by :

 @sorted_coll = @coll.sort_by { |obj| obj.created_at } 
+21
source share
 @coll1 = Model1.all @coll2 = Model2.all @coll = @coll1 + @coll2 @sorted_coll = @coll.sort_by { |a| a.created_at } 
+4
source share

you have a nested array inside the @coll variable. for example: http://codepad.org/jQ9cgpM1

try

 @sorted = @coll1 + @coll2 

then sort.

+2
source share

As Jed Schneider points out, the solution:

 @coll1 = Model1.all @coll2 = Model2.all @coll = @coll1 + @coll2 # use + instead of << 
0
source share

All Articles