我有一个对象报告,其中包含两个整数字段:Month和Year。 我需要按" date"
对其进行排序Report.desc(:year).desc(:month).each do |a|
puts a.year.to_s + " " + a.month.to_s
end
结果:
2011 12
2011 11
2012 7
2012 6
2012 5
2012 4
2012 3
2012 2
2012 1
虽然我会想到
2012 7
2012 6
2012 5
2012 4
2012 3
2012 2
2012 1
2011 12
2011 11
我做错了什么?
Mongoid Criteria看起来像:
irb(main):043:0> Report.desc(:year).desc(:month)
=> #<Mongoid::Criteria
selector: {},
options: {:sort=>{"year"=>-1, "month"=>-1}},
class: Report,
embedded: true>
答案 0 :(得分:4)
您获得的结果只按月份排序,而不是按整个日期排序(因此得到的结果)。也许使用sort_by方法和一个考虑年和月的主体? 类似的东西:
Report.sort_by{|t| [-t.year, -t.month]}
编辑:我使用年和月的负数来实现递减顺序。