Ruby on Rails ActiveRecord Query Interface Ordering


Example

You can order ActiveRecord query results by using .order:

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">]

If not specified, ordering will be performed in ascending order. You can specify it by doing:

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 also accepts a string, so you could also do

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">]

As the string is raw SQL, you can also specify a table and not only an attribute. Assuming you want to order users according to their role name, you can do this:

Class User < ActiveRecord::Base
    belongs_to :role
end

Class Role < ActiveRecord::Base
  has_many :users
end

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

The order scope can also accept an Arel node:

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