0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ActiveRecordで絶対値(abs)orderのやり方

Last updated at Posted at 2019-10-25

やり方

User.select("name, ABS(point) AS point_abs").order(:point_abs :desc)

データ内容補足

並び替え前

User  name    point
   1  neko    10
   2  dog     -20
   3  usagi   30

絶対値での並び替え後

User  name    point_abs
   3  usagi   30
   2  dog     -20
   1  neko    10

注意点

ActiveRecord::Relation上、列別名付けたカラムが表示されなくなる

User.select("name, ABS(point) AS point_abs").order(:point_abs :desc)
=> #<ActiveRecord::Relation[
     #<User id: 3, name: "usagi">,
     #<User id: 2, name: "dog">,
     #<User id: 1, name: "neko">]>

でもちゃんと項目としては存在している

User.select("name, ABS(point) AS point_abs").order(:point_abs :desc).to_a.first.point_abs
=> 30
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?