Reputation: 2946
I have an object Report that contains two integer fields: Month and Year. I need to sort it by "date"
Report.desc(:year).desc(:month).each do |a|
puts a.year.to_s + " " + a.month.to_s
end
results:
2011 12
2011 11
2012 7
2012 6
2012 5
2012 4
2012 3
2012 2
2012 1
While I would think to get
2012 7
2012 6
2012 5
2012 4
2012 3
2012 2
2012 1
2011 12
2011 11
What am I doing wrong?
The Mongoid Criteria looks like:
irb(main):043:0> Report.desc(:year).desc(:month)
=> #<Mongoid::Criteria
selector: {},
options: {:sort=>{"year"=>-1, "month"=>-1}},
class: Report,
embedded: true>
Upvotes: 2
Views: 2385
Reputation: 70929
The result you get is only sorted by month not by the whole date(thus the result you get). Maybe use the sort_by method with a body that takes into account both the year and the month? Something like:
Report.sort_by{|t| [-t.year, -t.month]}
EDIT: I am using the negatives of both the year and the month to achieve decreasing order.
Upvotes: 4