views:

347

answers:

2

How can I sort an array returned by an activerecord query by a 'created_at' date column? Keep in mind, this is once the query has been executed. Don't tell me to do it in the query because I need this to happen in the view.

Thanks

+5  A: 

Ruby includes support for sorting out of the box.

sorted = @records.sort_by &:created_at

However, this doesn't appear to have much to do with display and probably belongs in the controller.

Chuck
Enumerable#sort_by is great for this sort of thing, much better than the other example with Enumerable#sort.
tadman
thanks for the clarification. I've got multiple "entry points" to the same view, and the queries may or may not have the same sorting patterns (i know, not ideal). But isn't the order in which lists of stuff will be displayed not necessarily a "controller-only" feature?
tadman - care to elaborate? It's my understanding from the api docs that sort_by is the slower, more flexible, way of doing a sort. Great for more complex sorts, but too much for something this simple.
Bill D
@Bill D: That's pretty much opposite to the truth. `sort` is more flexible — you specify the entire comparison predicate, whereas with `sort_by` you just tell it *what* to compare and it does it using the default `sort` predicate. This case, where you call a method and sort based on the result, is quite common — `sort_by` is just a more concise way of writing that.
Chuck
Thanks, I'll have to go back and figure out how I misunderstood - I'm pretty sure I got the quick green checkmark, at any rate, only because I reluctantly obeyed his wish that I not berate him about doing this in the view.
Bill D
+2  A: 

Just call sort on the collection, passing in the block of code which tells ruby how you want it to sort:

collection.sort { |a,b| a.created_at <=> b.created_at }
Bill D
thanks a lot for the quick response