LoginSignup
27
22

More than 5 years have passed since last update.

あれっ?降順ってASC?DESC?そんな時は、reverse_orderを使ってみましょう!

Posted at

Railsは、デフォルトでは、primary keyの昇順でデータが取得されます。

例えば、primary keyがidのComment Modelがあったとすると、こうなります。

pry(main)> Comment.all
=>
[#<
  id: 1,
  content: "あ">,
 #<
  id: 2,
  content: "い">,
 #<
  id: 3,
  content: "う">
]

※分かりやすいように、改良しています。従って、実際のpryの表示とは異なります。

ここまでは、簡単です。次に、降順でデータを取得するとしましょう。
さて、どうコードを書きましょうか。

Comment.order(id: "DESC")
Comment.order("id DESC")
Comment.all.order(id: "DESC")
Comment.all.order("id DESC")
Comment.order(id: "ASC")
Comment.order("id ASC")
Comment.all.order(id: "ASC")
Comment.all.order("id ASC")

あれ?どれだっけ?となってなってしまうことがあります。
※ 上4つは、正解です。

そんな時は、reverse_orderを使ってみましょう!

reverse_order を使用すれば、悩むことなく、逆順に並び替えることができます!

ASC?DESC?と悩む必要は、ありません。最後にreverse_orderをつけとけばいいんです!

Comment.all で全部取得して、reverse_orderで逆順にする!

orderメソッドを使う時に、「あれ?all前につけとかないといけなかったっけ?」と悩むこともなくなります!

Comment.all.reverse_order

是非使ってみてください(笑)

27
22
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
22