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

FIELD関数でソートする時の記法忘れるのでメモっておく

Posted at

Rails でレコード取ってくるとき普段は ActiveRecord を使うと思うんですけど、たまに Arel を使う場面あると思います。「このレコードだけ前に出したい」とか「このタイプのレコードは後ろに持ってきたい」みたいな場合とかに MySQL の FIELD 関数使ったり。

んですけど、いつも記法忘れちゃうのでここでメモっておきます。多分将来のオレは今のオレに感謝すると思う。

Article モデルのレコードが 100 件ある場合。

Article.order([Arel.sql('field(articles.id, ?) DESC'), [10, 11, 12]]).pluck(:id)
# => [12, 11, 10, 1, 2, 3, 4, 5, ...]
Article.order([Arel.sql('field(articles.id, ?) ASC'), [10, 11, 12]]).pluck(:id)
# => [1, 2, 3, 4, 5, ..., 98, 99, 100, 10, 11, 12]

参考文献

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