LoginSignup
3
4

More than 3 years have passed since last update.

orderメソッド

Posted at

orderメソッド

orderメソッドは、並び順を変更するメソッドです。
【例】モデルをTweetとします。

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

上記で設定できます。
並び替えの基準にはASC(昇順)とDESC(降順)の2種類があり、ASCは値が古いものから新しいのものになり、DESCはその逆で新しいものから古いものになります。
今回はcreated_at(作成日時)をDESCしてみます。

app/controllers/tweets_controller.rb
〜省略〜
  def index
    @tweets = Tweet.includes(:user).order("created_at DESC")
  end
〜省略〜

上記でTweet.includes(:user)はN+1問題の解消、order("created_at DESC")でcreated_at(作成日時)が投稿したときに新しいものから古い順になります。

3
4
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
3
4