Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort collection by created_at attribute

I'm working with Ruby on Rails 2.3.8 and I've got a collection that is built from other two collections, as follows:

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

@coll = @coll1 << @coll2

Now, I would like to sort that collection by created_at attribute in descendant order. So, I did the following:

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

And I've got the following exception:

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

eventhought it exists for those models.

Could anyboy help me please?

like image 591
Brian Roisentul Avatar asked Dec 06 '10 19:12

Brian Roisentul


People also ask

How do you sort a method in Ruby?

The Ruby sort method works by comparing elements of a collection using their <=> operator (more about that in a second), using the quicksort algorithm. You can also pass it an optional block if you want to do some custom sorting. The block receives two parameters for you to specify how they should be compared.

How do you sort an array of objects in Ruby?

You can use the sort method on an array, hash, or another Enumerable object & you'll get the default sorting behavior (sort based on <=> operator) You can use sort with a block, and two block arguments, to define how one object is different than another (block should return 1, 0, or -1)


2 Answers

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

Flatten the resulting array:

@coll.flatten!

Or preferably just use the + method:

@coll = @coll1 + @coll2

And for sorting you should use sort_by:

@sorted_coll = @coll.sort_by { |obj| obj.created_at }
like image 188
Jacob Relkin Avatar answered Sep 18 '22 10:09

Jacob Relkin


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

@coll = @coll1 + @coll2

@sorted_coll = @coll.sort_by { |a| a.created_at } 
like image 22
nunopolonia Avatar answered Sep 19 '22 10:09

nunopolonia