按字母顺序排列ActiveRecord结果

时间:2015-10-13 13:02:06

标签: sql ruby-on-rails activerecord sql-order-by rails-activerecord

我有一个像这样的控制器方法:

def index
  @categories = Category.all
end

如何按字母顺序排列@categories个名字?

3 个答案:

答案 0 :(得分:6)

您可以order

@categories = Category.order(:name)

答案 1 :(得分:1)

在你的类别控制器中:

@Getter @Setter private String foo;

默认情况下,这会按字母顺序排列 class CategoriesController < ApplicationController def index @categories = Category.order(:name) end end 列。

答案 2 :(得分:0)

#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