Walksalong
Walksalong

Reputation: 191

Ruby or Rails sort on two/multiple date fields

Seems simple enough- I'd like to combine two model queries and sort them all by date DESC, but the date fields are named differently.

@news_and_posts = [News.all(:limit => 3, :order => "date_of_news DESC") + Post.all(:limit => 3, :order => "date_of_post DESC") 

I've tried

@news_and_posts = [News.all(:limit => 3, :order => "date_of_news DESC") + Post.all(:limit => 3, :order => "date_of_post DESC").sort_by {|n, p| [n.date_of_news, p.date_of_post]}

Thanks!

Upvotes: 3

Views: 975

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

You should use an alias returning the date (a method called 'date' for example) implemented in each model you want to compare.

Then sort your list by this date :

(Thanks to @tokland for a better implementation)

my_collection.sort_by(&:date)

Upvotes: 4

Related Questions