This seems like a really simple question but I haven’t seen it answered anywhere.
In rails if you have:
class Article < ActiveRecord::Base has_many :comments end class Comments < ActiveRecord::Base belongs_to :article end
Why can’t you order the comments with something like this:
@article.comments(:order=>'created_at DESC')
Named scope works if you need to reference it a lot and even people do stuff like this:
@article.comments.sort { |x,y| x.created_at <=> y.created_at }
But something tells me it should be simpler. What am I missing?
You can specify the sort order for the bare collection with an option on
has_manyitself:Or, if you want a simple, non-database method of sorting, use sort_by:
Collecting this with the ActiveRecord-added methods of ordering:
Your mileage may vary: the performance characteristics of the above solutions will change wildly depending on how you’re fetching data in the first place and which Ruby you’re using to run your app.