Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/Rails sort_by date desc, name asc

I'm creating a list page of two different classes and I'd like to sort them by date desc, name asc. Both have datetime fields with a date method in each model.

posts = Post.all
news = News.all
@news_and_posts = posts.zip(news).compact.select(&:date).sort {|x| [-x.date, x.name]}

This throws a NoMethodError: undefined method `-@' for Tue, 11 Nov 2014:Date

On several other questions this answer was given within both sort_by and sort, but I'm not having any luck.

Rails 4.0.5 Ruby 2.1.3

like image 897
Walksalong Avatar asked Dec 25 '22 02:12

Walksalong


1 Answers

A couple things. First, you should use sort_by in your example above, because the block takes one parameter as you used. The sort block takes two - item A and item B, for comparison. Next, you can get what you want by subtracting the date from something significant, like today's date:

objects.sort_by {|x| [Date.today - x.date, x.name]}

Even if dates might be in the future, the math will still work.

These pages detail the difference between sort and sort_by:

http://rubycuts.com/enum-sort

http://rubycuts.com/enum-sort-by

Btw, I agree with other commenters that you really should be ordering these records in your database query itself, but I wanted to solve the specific problem you asked about.

like image 51
Jaime Bellmyer Avatar answered Jan 12 '23 02:01

Jaime Bellmyer