Brian Roisentul
Brian Roisentul

Reputation: 4730

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?

Upvotes: 13

Views: 15785

Answers (4)

Jacob Relkin
Jacob Relkin

Reputation: 163228

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 }

Upvotes: 26

yfeldblum
yfeldblum

Reputation: 65435

As Jed Schneider indicates, the solution is:

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

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

Upvotes: 0

nunopolonia
nunopolonia

Reputation: 14417

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

@coll = @coll1 + @coll2

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

Upvotes: 4

Jed Schneider
Jed Schneider

Reputation: 14671

you have a nested array inside your @coll variable. like so: http://codepad.org/jQ9cgpM1

try

@sorted = @coll1 + @coll2

then sort.

Upvotes: 2

Related Questions