Flowdock
method

order

Importance_4
Ruby on Rails latest stable (v4.0.2) - 4 notes - Class: ActiveRecord::QueryMethods
order(*args) public

Allows to specify an order attribute:

User.order('name')
=> SELECT "users".* FROM "users" ORDER BY name

User.order('name DESC')
=> SELECT "users".* FROM "users" ORDER BY name DESC

User.order('name DESC, email')
=> SELECT "users".* FROM "users" ORDER BY name DESC, email

User.order(:name)
=> SELECT "users".* FROM "users" ORDER BY "users"."name" ASC

User.order(email: :desc)
=> SELECT "users".* FROM "users" ORDER BY "users"."email" DESC

User.order(:name, email: :desc)
=> SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC
Show source
Register or log in to add new notes.
March 27, 2012
3 thanks

Reorder

If you want to override previously set order (even through default_scope), use reorder() instead.

E.g.

User.order('id ASC').reorder('name DESC')

would ignore ordering by id completely

October 28, 2014
1 thank

Ordering on associations

For ordering on the attribute of an associated model you have to include it:

Package.includes(:package_size).order("package_sizes.sort_order")
January 12, 2014
0 thanks

using hash as order

order can be specified as a hash, e.g.:

order(id: :desc)

This will prevent “ambiguous column” errors when the order is used with joins or includes.

October 30, 2014 - (v3.0.0 - v3.2.13)
0 thanks

Order with hash parameters only in ActiveRecord >= 4.0

If you use order with hash parameters on AR3 versions it wont work.