Rails: Order by DESC

Three different ways to get data from a Model and group by descending order.

Rails: Order by DESC

I wanted to present three different ways to get data from a Model and arrange it in descending order. Below are a few examples of how to get data from a Keyword model.

Method #1 - Using a Controller

Path: app/controllers/keywords_controller.rb

At the controller level, you can make a request using the order method.

class KeywordsController < ApplicationController
  before_action :set_keyword, only: [:show, :edit, :update, :destroy]

  # GET /keywords
  # GET /keywords.json
  def index
    @keywords = Keyword.all.order("created_at DESC")

    # Use callbacks to share typical setup or constraints between actions.
    def set_keyword
      @keyword = Keyword.find(params[:id])

    # Never trust parameters from the scary internet, only allow the white list through.
    def keyword_params

Method #2 - Using a Model

Path: app/models/keyword.rb

Here's how to order a list of objects within a Model.

class Keyword < ApplicationRecord
  default_scope { order(created_at: :desc)}

Method #3 - Using a View

Scoping Technique

From within the model, you must first create a scope.

Path: app/models/keyword.rb

scope :desc, order(name: :desc)

Path: app/views/keywords/index.html.erb

<%= render @keywords.desc %>

Alternative Queries

Pass a column name to .order with the direction as a value. I think this is the best method because of its :symbol use.

Keyword.order(name: :desc)
Keyword.order("name DESC")
Keyword.order('keywords.name DESC')