订购

你可以使用 .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)