LoginSignup
28
21

More than 5 years have passed since last update.

Railsで他のテーブルのカラムをソートする方法

Posted at

はじめに

Railsで取得した値を並び替えする際には、orderメソッドを使うのが一般的だと思います。
ただ、他のテーブルから取得した値をソートする際にちょっとハマったのでメモを残しました。

1つのテーブルでソートする場合

リファレンスにもありますがこちらは非常にわかりやすいです。

モデル.order("カラム名 DESC")

別のテーブルのカラムをソートする場合

例えば、projectモデルのdateカラムをソートする場合
結論からいうと下記のように書けばうまく行きました。

モデル.includes(:project).order("projects.date DESC")

ポイントはorderの中では複数形で書くといいそうです。

参考

Belongs toしているテーブルのカラムでソートする

28
21
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
28
21