Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 731
Walksalong Avatar asked Dec 20 '25 23:12

Walksalong


1 Answers

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)
like image 134
MrYoshiji Avatar answered Dec 22 '25 14:12

MrYoshiji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!