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

ツイートを最新順に並び替え方法について

Last updated at Posted at 2019-06-08

最新のツイートが一番上に来るように表示させる方法

orderメソッドを使う

orderメソッドは、テーブルから取得してきた複数のインスタンスを並び替えるメソッドである。

allメソッドを利用した場合、通常であればレコードはid順に取得される。しかし、以下のようにorderメソッドの引数として("id DESC")とした場合、レコードは逆順に並び替えることができる。
orderメソッドは引数として**("テーブルのカラム名 並び替える順序")**という形をとる。並び替える順序には、ASC(昇順)とDESC(降順)の2種類がある。

controllers/tweets_controller.rb


def index
    @tweets = Tweet.all.order("id DESC")
end

ツイートが作成された日時は、DB上created_atカラムに保存される。そのため、以下のように()内を変更すればよい。

controllers/tweets_controller.rb


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

orderメソッドを使用することで、自動的にカラムが追加されていくので、allメソッドは省略してもよい。

                                 以上

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?