LoginSignup
0
0

表示順を並び替える

Posted at

image.png
1:レコードの取得順を変える
ツイートを並び替える方法は、表示のときに順番を変えるのではなく、情報を取得するタイミングで先に並び替えます。

2:orderオーダーメソッド
モデルが使用できる、ActiveRecordメソッドの1つです。
orderメソッドは、テーブルから取得してきた複数のレコード情報を持つインスタンスの、並び順を変更するメソッドです。

引数には、"並び替えの基準となるカラム名 並び順"のように「並び替えの基準となるカラム名」と「並び順」を半角スペースで繋げて指定します。

orderメソッドは、複数のレコード情報を取得する文に続けて以下のように使用します。

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

並び順にはそれぞれAscending/Descendingの略でASC(昇順)とDESC(降順)の2種類があります。
①並び順:ASC(昇順) 内容:小さいものから大きいものになる。古いものから新しいのものになる。
②並び順:DESC(降順) 内容:ASCの反対。大きいものから小さいものになる。新しいものから古いものになる。

記述例:下記のようにorderメソッドの引数として("created_at DESC")とすれば、レコードは降順に並び替えられます。
app/controllers/tweets_controller.rb

class TweetsController < ApplicationController
  before_action :set_tweet, only: [:edit, :show]
 before_action :move_to_index, except: [:index, :show]

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

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