Ordering
suggest changeOrder an Active Record relation with 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">]
The default direction is ascending. Set it explicitly with:
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 SQL fragment. Keep it a literal. Do not interpolate request input into this string.
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">]
The fragment can name a table. To order users by their role name:
class User < ActiveRecord::Base
belongs_to :role
end
class Role < ActiveRecord::Base
has_many :users
end
User.includes(:role).order("roles.name ASC")
order also accepts an Arel node. This one sorts on users.name, not roles.name:
User.includes(:role).order(User.arel_table[:name].asc)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents