LoginSignup
1
0

More than 1 year has passed since last update.

【Ruby】投稿一覧の表示の順番を変更する

Last updated at Posted at 2021-05-07

概要

投稿アプリを作成している時、投稿が表示される順番を変えたい時ってありますよね。
その際、「新しい順の投稿一覧」を表示する場合と「古い順の投稿一覧」を表示する場合の方法を記載しておきます!

環境

ruby 2.6.5
Rails 6.0.3.5

「新しい順の投稿一覧」

controllers>comments.controller.rb
class CommentsController < ApplicationController
  def index
    @comments = Comment.all
  end

@comments = Comment.allと記載がある後ろにorder(created_at: :desc)を書きます。
(allは記述しなくて平気です)

controllers>comments.controller.rb
class CommentsController < ApplicationController
  def index
    @comments = Comment.order(created_at: :desc) #created_atは作成日時 descは降順
  end

これで完了です。新しい投稿が上から表示されます!

「古い順の投稿一覧」

controllers>comments.controller.rb
class CommentsController < ApplicationController
  def index
    @comments = Comment.order(created_at: :asc) #created_atは作成日時 ascは昇順
  end

これで完了です。古い投稿から表示されます!

まとめ

#新しい順の投稿一覧
order(created_at: :desc) #created_atは作成日時 descは降順
#古い順の投稿一覧
order(created_at: :asc) #created_atは作成日時 ascは昇順

1
0
2

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