LoginSignup
0
0

More than 3 years have passed since last update.

取得するレコードを最新順表示にする方法

Last updated at Posted at 2020-08-13

取得するレコードの順番を変える

ツイートを並び替える方法は、表示の時に順番を変えるのではなく、情報を取得するタイミングで先に並び替えておきます。

order メソッドを使用する

【例】

インスタンス = モデル名.all.order("並び替えの基準となるカラム名 並び順")

並び順にはそれぞれAscending/Descendingの略でASC(昇順)とDESC(降順)の2種類があり、値が「小さいものから大きいものになる」または「古いものから新しいのものになる」場合は昇順、その逆は降順を使います。

tweets_controller.rbを以下のように編集

レコードが作成された日時情報を持つcreated_atカラムを基準に並び替えます。

tweets_controller.rb
 def index
   @tweets = Tweet.includes(:user).order("created_at DESC")
 end

orderメソッドの引数として("created_at 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