LoginSignup
5
6

More than 5 years have passed since last update.

Railsのwhereで検索した際に、指定の順番通りにデータを取得する方法

Posted at

問題

RailsのActiveRecordを使い、(例えば)IDで検索した際に順番どおりにデータを引っ張ってこれない。

> User.where(id: [4,6,2,9,7]).pluck(:id)
=> [2, 4, 6, 7, 9]
# 理想としては [4,6,2,9,7] となって欲しい

解決

そこで登場するのが、order_as_specifiedというgemである。
order_as_specified:https://github.com/panorama-ed/order_as_specified

使い方はシンプル。使いたいモデルに下記のコードを入れる

class User < ActiveRecord::Base
  extend OrderAsSpecified



end

それで、こんなふうに書くと、思い通りの順番になる。


> User.where(id: [4,6,2,9,7]).order_as_specified(id: [4,6,2,9,7]).pluck(:id)
=> [4,6,2,9,7]

もちろん、ID以外でもできるので、

.order_as_specified(id: [4,6,2,9,7])

の部分をいじってやる。
実際に、生成されるsql文は下記の用になるので、なかなかSQL的には辛いなーとおもいました。

> User.where(id: [4,6,2,9,7]).order_as_specified(id: [4,6,2,9,7]).to_sql
=> "SELECT `users`.* FROM `users` WHERE `users`.`id` IN (4, 6, 2, 9, 7)  ORDER BY users.id='4' DESC, users.id='6' DESC, users.id='2' DESC, users.id='9' DESC, users.id='7' DESC"
5
6
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
5
6