LoginSignup
7
7

More than 5 years have passed since last update.

Rails の reverse_order を使ってみた

Posted at

Rails で reverse_order を使ってあれこれと試してみたのでメモ。

バージョン

  • ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]
  • Rails 5.1.6

order のおさらい

DBから取得するデータをソートするには order を使います。( scope の中なのはたまたまです)

model/article.rb
class Article < ApplicationRecord
  scope :sort_by_oldest, -> {
    order(:published_date)
  }
end

order(:published_date)order('published_date') では作られるSQLが異なるため要注意。

-- order(:published_date)
ORDER BY `articles`.`published_date` ASC

-- order('published_date')
ORDER BY published_date

リレーションを上手く扱ってくれるのが Rails の魅力。
SQLを直接書くと思わぬ落とし穴にはまりかねないので、なるべく避けたいところです。

降順に取得するにはどうすればいいの?

良く見かけるのは以下のような書き方です。

model/article.rb
class Article < ApplicationRecord
  scope :sort_by_newest, -> {
    order('published_date DESC')
  }
end

SQL書きたくない言ってる端からこれですよ。。

reverse_order 登場

そこで reverse_order の登場です。降順に取得したい場合は下記のように書けます。

model/article.rb
class Article < ApplicationRecord
  scope :sort_by_newest, -> {
    order(:published_date)
      .reverse_order
  }
end

なるほど。 reverse_order は「降順」に取得するメソッドなんですね!
→ 違います。

正しい reverse_order の意味

降順とかじゃなく、現在のソート順を逆にするメソッドです。名前のままですが(笑)

# ORDER BY `table`.`col_one` DESC
order(:col_one)
  .reverse_order

# ORDER BY `table`.`col_one` DESC, `table`.`col_two` ASC
order(:col_one)
  .reverse_order
  .order(:col_two)

# ORDER BY `table`.`col_one` ASC, `table`.`col_two` DESC
order(:col_one)
  .reverse_order
  .order(:col_two)
  .reverse_order

# ORDER BY `table`.`col_one` DESC, `table`.`col_two` DESC
order(:col_one)
  .order(:col_two)
  .reverse_order
7
7
0

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
7
7