0
0
RailsHow-ToBeginner · 3 min read

How to Use order Method in Rails for Sorting Records

In Rails, use the order method on ActiveRecord queries to sort records by one or more columns. You can specify columns with directions like asc or desc, for example: Model.order(created_at: :desc) to get records sorted by newest first.
📐

Syntax

The order method sorts query results by one or more columns. You can pass a hash with column names as keys and sorting directions (:asc or :desc) as values. Alternatively, you can pass a string with SQL order clauses.

  • Model.order(column: :asc) - sorts by column ascending
  • Model.order(column: :desc) - sorts by column descending
  • Model.order('column1 DESC, column2 ASC') - sorts by multiple columns with directions
ruby
Model.order(created_at: :desc)
Model.order(name: :asc)
Model.order('created_at DESC, name ASC')
💻

Example

This example shows how to fetch users sorted by their signup date from newest to oldest, and then by their name alphabetically.

ruby
class User < ApplicationRecord
end

# Fetch users ordered by signup date descending, then name ascending
users = User.order(created_at: :desc, name: :asc)

users.each do |user|
  puts "#{user.name} signed up at #{user.created_at}"
end
Output
Alice signed up at 2024-06-01 10:00:00 Bob signed up at 2024-05-30 09:30:00 Charlie signed up at 2024-05-30 09:30:00
⚠️

Common Pitfalls

Common mistakes when using order include:

  • Passing symbols without directions, which defaults to ascending but can be unclear.
  • Using strings without sanitizing input, risking SQL injection.
  • Chaining multiple order calls, where only the last one applies.

Always specify directions explicitly and combine multiple columns in one order call.

ruby
# Wrong: chaining order calls, only last applies
User.order(:name).order(created_at: :desc)

# Right: combine in one order call
User.order(name: :asc, created_at: :desc)
📊

Quick Reference

UsageDescription
Model.order(column: :asc)Sorts records by column ascending
Model.order(column: :desc)Sorts records by column descending
Model.order('column1 DESC, column2 ASC')Sorts by multiple columns with directions
Model.order(:column)Sorts by column ascending (default)
Model.order(nil)Removes ordering from query

Key Takeaways

Use order with column names and directions (:asc or :desc) to sort records.
Combine multiple columns in a single order call for multi-level sorting.
Avoid chaining multiple order calls as only the last one takes effect.
Be cautious with raw SQL strings in order to prevent SQL injection.
Default sorting direction is ascending if not specified.