我有一個控制器的方法是這樣的:訂購ActiveRecord的結果按字母順序
def index
@categories = Category.all
end
如何訂購@categories
名稱的字母順序?
我有一個控制器的方法是這樣的:訂購ActiveRecord的結果按字母順序
def index
@categories = Category.all
end
如何訂購@categories
名稱的字母順序?
您可以order
:
@categories = Category.order(:name)
在你類別控制器:
class CategoriesController < ApplicationController
def index
@categories = Category.order(:name)
end
end
這將默認順序:name
列的字母順序排列。
#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