skip to content

In Active Record, how do order, reorder, reverse_order and in_order_of differ when sorting a list of restaurants?

level: middleimportance: should knowfreq 45%

answer

  1. order appends, it never replaces
  2. reorder discards earlier orders
  3. reverse_order flips each direction
  4. in_order_of builds a CASE
  5. UnknownAttributeReference for raw strings

basics

~10 s

order appends sort keys to any already present, reorder replaces them, reverse_order flips every direction, and in_order_of sorts (and by default filters) rows by an explicit list of values using a CASE expression.

solid answer

~40 s

`order(rating: :desc)` adds `ORDER BY rating DESC`, and a later `order(:name)` is appended as a secondary key, so a scope that already sorts by `created_at` keeps winning. `reorder(rating: :desc)` throws away every earlier order, including a scope's or a `default_scope`'s, and installs the new one. `reverse_order` flips each existing direction, falling back to the model's implicit order column and primary key when there is none, and raises `ActiveRecord::IrreversibleOrderError` for strings it cannot invert. `in_order_of(:id, ids)` returns rows in the order of a Ruby list, for example ids ranked by a search service, by adding `WHERE id IN (...)` and `ORDER BY CASE ... END`; `filter: false` keeps the other rows and sorts them last. Hash and symbol arguments are safe; a raw SQL string that is not a plain column reference raises `ActiveRecord::UnknownAttributeReference`.

code

ruby · 14 lines
ruby
class Restaurant < ApplicationRecord
  scope :newest, -> { order(created_at: :desc) }
end

Restaurant.newest.order(rating: :desc)
# ORDER BY created_at DESC, rating DESC   (date still wins)

Restaurant.newest.reorder(rating: :desc)
# ORDER BY rating DESC

ranked_ids = [42, 7, 19]  # from a search service
Restaurant.in_order_of(:id, ranked_ids)
# WHERE id IN (42, 7, 19)
# ORDER BY CASE WHEN id = 42 THEN 1 WHEN id = 7 THEN 2 WHEN id = 19 THEN 3 END ASC

go deeper

for a junior

Know that order(rating: :desc) sorts descending, several keys go in one call, and a second order call adds a tiebreaker rather than replacing the first.

for a middle

Explain reorder versus order with scopes, how reverse_order and last flip directions, and what in_order_of generates, including filter: false.

for a senior

Guard user-chosen sorts with allow-lists, spot inherited orders that hide a new one, and know which string orders cannot be reversed.

for a principal

Keep sort semantics in named scopes with clear ownership, so a default order inherited from a scope never silently overrides what a screen asks for.

## order: appending sort keys `order` accepts symbols, hashes and simple strings: ```ruby Restaurant.order(:name) # ORDER BY restaurants.name ASC Restaurant.order(rating: :desc, name: :asc) # ORDER BY rating DESC, name ASC Restaurant.order("name DESC") # ORDER BY name DESC ``` The direction in a hash must be `asc` or `desc`, in lower or upper case, as a symbol or a string; anything else raises `ArgumentError`. Each `order` call **appends** to the list: ```ruby Restaurant.order(:created_at).order(rating: :desc) # ORDER BY created_at ASC, rating DESC ``` That is the root of a classic bug: a scope or association that sorts by `created_at` is chained with `order(rating: :desc)`, and the page still appears sorted by date, because `created_at` is the primary key of the sort and `rating` only breaks ties. ## reorder: replacing the sort `reorder` discards every existing order value and installs the new one: - `Restaurant.newest.reorder(rating: :desc)` sorts only by rating, whatever `newest` did. - It also overrides an order that came from a `default_scope` or an association's scope. - Later `order` calls append to the reordered list again. `unscope(:order)` removes ordering entirely, which is occasionally useful before a calculation. ## reverse_order: flipping directions `reverse_order` inverts each sort key: `ASC` becomes `DESC` and vice versa. It powers `last`, and is handy for a "lowest rated" toggle. Rules: 1. With **no order**, it sorts by `implicit_order_column` and the primary key, descending. 2. With symbol or hash orders, it flips each Arel node. 3. With **strings**, it rewrites trailing `ASC`/`DESC`. A string using `NULLS FIRST`/`NULLS LAST`, or a function with several arguments, cannot be inverted safely and raises `ActiveRecord::IrreversibleOrderError`. ## in_order_of: an explicit list Sometimes the order comes from outside the database: ids ranked by a search engine, or statuses in a business-defined sequence. `in_order_of(column, values)`: | Option | SQL effect | |---|---| | default (`filter: true`) | `WHERE column IN (values)` plus `ORDER BY CASE WHEN column = v1 THEN 1 ... END` | | `filter: false` | no WHERE; unmatched rows get `ELSE n+1` and come last | | `nil` in the list | adds `OR column IS NULL` and a `WHEN column IS NULL` branch | | empty list | returns a `none` relation | It works with enum columns too, mapping enum names to their stored values. It is the Rails answer to "load these ids and keep this order" without sorting in Ruby after the query. ## Raw SQL in order Strings are passed to the database, so Active Record allows only plain column names and simple `function(column)` expressions with an optional direction. Anything else raises `ActiveRecord::UnknownAttributeReference` ("Dangerous query method ... called with non-attribute argument(s)"). Two consequences: - **Never** pass `params[:sort]` straight into `order`. Map it through an allow-list: `{ "rating" => { rating: :desc }, "name" => :name }.fetch(params[:sort], :name)`. - Trusted complex expressions must be marked as SQL explicitly, a separate topic. ## Debugging an unexpected sort When a page sorts wrongly, check what the relation actually carries before changing anything: 1. Print `relation.to_sql` and read the full `ORDER BY`, not just the last key you added. 2. Look for orders contributed by a scope, a `default_scope` or the association's own `-> { order(...) }` lambda; they come **first** in the list. 3. Decide whether you want to add a tiebreaker (`order`) or take over the sort (`reorder`). 4. If `last` or `reverse_order` raises `IrreversibleOrderError`, rewrite the string order with symbols or a hash, or reverse it by hand. ## Choosing - Adding a tiebreaker: `order`. - Overriding a sort you inherited from a scope: `reorder`. - Flipping a known order: `reverse_order`. - Following an external ranking: `in_order_of`.

  • How would you let users choose the sort column from a query parameter safely?
    Map the parameter through an allow-list to hash or symbol orders, for example `SORTS = { "rating" => { rating: :desc }, "name" => { name: :asc } }` and `Restaurant.order(SORTS.fetch(params[:sort], { name: :asc }))`. Never pass the raw string, which either raises `ActiveRecord::UnknownAttributeReference` or, if it looks like a column, sorts by something the user picked.
  • Why does Restaurant.order("rating DESC NULLS LAST").last raise?
    `last` needs `reverse_order`, and Rails cannot safely invert a string containing `NULLS LAST`, so it raises `ActiveRecord::IrreversibleOrderError`. Use `first` with the opposite order written out, or express the order through Arel nodes that know how to reverse themselves.

  • A second order call replaces the first one
  • reorder only changes the direction of the existing sort
  • in_order_of sorts the loaded records in Ruby
  • order(params[:sort]) is safe because Rails escapes strings
  • reverse_order on an unordered relation leaves the query unsorted