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

Rails で DB から取得するデータに対し order が効かない場合

Posted at

修正前

  • 条件に応じてソート方法を分岐させたくて以下のように実装
    • しかし機能しなかった
修正前
def search
    result = Post.all.order(created_at: :desc)
    if #-条件-#
        result = result.order(:created_at)
    end
end

修正後

  • 以下のように修正したら機能
修正後
def search
    result = Post.all
    if #-条件-#
        result = result.order(:created_at)
    end
end

メモ

  • この場合は Post.all の時点で「id の降順」になっているので、実質「created_at の降順」であったので余計な order になっていた
1
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
1
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?