LoginSignup
0
0

More than 1 year has passed since last update.

ActiveRecordで、特定のidを先頭に持ってきて並び替える

Last updated at Posted at 2022-12-23

前提と注意

  • MySQLでしか確認していない
  • 渡ってきたパラメータをそのまま(user_idとして)使うとSQLインジェクションが発生しうる。安全な値であることを担保できない場合はこの方法は使うべきではないと思う。

特定のidを先頭に持ってきたい

user_id = 5 # 特定のidは5とする
users = User.order(Arel.sql("users.id = #{ user_id } DESC")) 

その後に別の並び替え条件を指定したい

特定のidを先頭にしつつ、そのあとはpriority順で並び替えたい

users = User.order(Arel.sql("users.id = #{ user_id } DESC,
                             users.priority DESC")) 

さらにその後に別の並び替え条件を指定したい

特定のidを先頭にしつつ、そのあとはpriority順、そのあと(priorityが同じだったもの)はpriority2順で並び替えたい

users = User.order(Arel.sql("users.id = #{ user_id } DESC,
                             users.priority DESC,
                             users.priority2 DESC"))
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