Rails 8.2 adds Relation#default_order

Rails 8.2 adds default_order to Active Record relations. It provides a default sort that applies only when the query has no explicit order. The feature is currently available on Rails main, not in Rails 8.1.4.

Consider a catalog that lists products by name, but also lets us sort by price. Our products are Apron at 30, Mug at 10, and Notebook at 20.

Before

Calling order on an already ordered relation adds another sort column. The original column still takes priority:

products = Product.order(:name)

products.order(:price).pluck(:name)
# => ["Apron", "Mug", "Notebook"]

We need reorder to replace the name sort with the price sort:

products.reorder(:price).pluck(:name)
# => ["Mug", "Notebook", "Apron"]

After

With default_order, we can provide the name sort as a fallback:

products = Product.default_order(:name)

products.pluck(:name)
# => ["Apron", "Mug", "Notebook"]

products.order(:price).pluck(:name)
# => ["Mug", "Notebook", "Apron"]

The explicit order(:price) replaces the fallback entirely. It does not keep name as a secondary sort. If prices can tie, we can make the ordering predictable with order(:price, :id).

We can also put the fallback in a scope:

class Product < ApplicationRecord
  scope :for_catalog, -> { default_order(:name) }
end

Product.for_catalog.order(:price).pluck(:name)
# => ["Mug", "Notebook", "Apron"]

This lets the scope provide a default without requiring every caller to know about reorder. Existing order calls still append to other explicit order calls.

These examples were tested with Ruby 4.0.6, SQLite, Active Record 8.1.4 for the old approach, and Rails main at e9aab74 for default_order. Rails 8.2 is unreleased at the time of writing.

See the default_order pull request and the Active Record query documentation.

Need expert help with Rails database work?

Saeloun is a Rails Foundation Contributing Member helping teams modernize, upgrade, scale, and maintain production Rails applications.

Our Expertise

  • Rails contributors
  • 500+ Technical Articles
  • Production Rails consulting
  • Performance Optimization

Services

  • Rails application development
  • Code Audits
  • Rails upgrades
  • Team Augmentation

Need help on your Ruby on Rails or React project?

Join Our Newsletter