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?
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.
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)
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 }
@coll1 = Model1.all
@coll2 = Model2.all
@coll = @coll1 + @coll2
@sorted_coll = @coll.sort_by { |a| a.created_at }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With