Chris Mendez in For Developers, Ruby

Rails: Order by DESC

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

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")
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def keyword_params
      params.require(:keyword).permit(:word)
    end

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)}
end  

View

Method

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).reverse_order  
Keyword.order("name DESC")  
Keyword.order('keywords.name DESC')  
Keyword.all.sort_by(&:name).reverse  

Resources