2

月と年の2つの整数フィールドを含むオブジェクトレポートがあります。「日付」で並べ替える必要があります

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

私は何が間違っているのですか?

MongoidCriteriaは次のようになります。

irb(main):043:0> Report.desc(:year).desc(:month)

    => #<Mongoid::Criteria
       selector: {},
       options:  {:sort=>{"year"=>-1, "month"=>-1}},
       class:    Report,
       embedded: true>
4

1 に答える 1

4

取得する結果は、日付全体ではなく月でのみ並べ替えられます(したがって、取得する結果)。たぶん、年と月の両方を考慮した本体でsort_byメソッドを使用しますか?何かのようなもの:

Report.sort_by{|t| [-t.year, -t.month]}

編集:私は降順を達成するために年と月の両方のネガを使用しています。

于 2012-07-31T07:22:03.943 に答える