user4932805
user4932805

Reputation:

Order ActiveRecord results alphabetically

I have an controller method like this:

def index
  @categories = Category.all
end

How do I order @categories names alphabetically?

Upvotes: 5

Views: 5863

Answers (3)

C dot StrifeVII
C dot StrifeVII

Reputation: 1885

#default ascending

  class CategoriesController < ApplicationController

    def index
      @categories = Category.order(:name)
    end
  end

#explicit ascending if you were chaining a scope that has some other default order

  class CategoriesController < ApplicationController

    def index
      @categories = Category.tags.order(name: :asc)
    end
  end

#decending

 class CategoriesController < ApplicationController

   def index
     @categories = Category.tags.order(name: :desc)
   end
 end

Upvotes: 0

Cyzanfar
Cyzanfar

Reputation: 7146

In you Categories Controller:

 class CategoriesController < ApplicationController

     def index
         @categories = Category.order(:name)
     end
  end

This will by default order the :name column in by alphabetical order.

Upvotes: 2

potashin
potashin

Reputation: 44611

You can order:

@categories = Category.order(:name)

Upvotes: 9

Related Questions