LoginSignup
2
1

More than 1 year has passed since last update.

【Rails】レコードを配列の順番に並び替える

Last updated at Posted at 2022-04-25

初めに

環境

Rails 7.0.2
Ruby 3.1.1

やりたいこと

配列の順番にレコードを並び替える。

本文

通常 where に配列を渡して、レコードを取得すると id 順に並び替えられて取得されます。
ですがin_order_ofを使用することで配列の順番に並び替えられます。

arr = [11,2,4,6,8,1]

users = User.where(id: arr)
# puts users.ids -> [1,2,4,6,8,11]


users = User.where(id: arr).in_order_of(:id ,arr)
# puts users.ids -> [11,2,4,6,8,1]

ちなみに Rails 7.0.0になってから追加されたメソッドでデータベースが Mysqlpostgresql でも関係なく動きます。

参考

in_order_of - Rails ドキュメント

ソースコード - Github

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