訂購

你可以使用 .order 訂購 ActiveRecord 查詢結果 : ****

User.order(:created_at)
#=> => [#<User id: 2, created_at: "2015-08-12 21:36:23">, #<User id: 11, created_at: "2015-08-15 10:21:48">]

如果未指定,將按升序執行排序。你可以通過這樣做來指定它:

User.order(created_at: :asc)
#=> => [#<User id: 2, created_at: "2015-08-12 21:36:23">, #<User id: 11, created_at: "2015-08-15 10:21:48">]

User.order(created_at: :desc)
#=> [#<User id: 7585, created_at: "2016-07-13 17:15:27">, #<User id: 7583, created_at: "2016-07-13 16:51:18">]

.order 也接受一個字串,所以你也可以這樣做

User.order("created_at DESC")
#=> [#<User id: 7585, created_at: "2016-07-13 17:15:27">, #<User id: 7583, created_at: "2016-07-13 16:51:18">]

由於字串是原始 SQL,因此你還可以指定表而不僅僅是屬性。假設你想根據他們的 role 名稱訂購 users,你可以這樣做:

Class User < ActiveRecord::Base
    belongs_to :role
end

Class Role < ActiveRecord::Base
  has_many :users
end

User.includes(:role).order("roles.name ASC")

order 範圍也可以接受 Arel 節點:

User.includes(:role).order(User.arel_table[:name].asc)