How to Use Order in Ruby on Rails

09/19/2021

Contents

In this article, you will learn how to use order in Ruby on Rails.

How to use order

The order method in Rails is used to sort the records of a model in a specific order. It takes one or more arguments to specify the order of sorting. Here are some examples of how to use the order method in Rails:

Sort records in ascending order based on a single attribute:
# Get all users sorted by their name in ascending order
@users = User.order(:name)
Sort records in descending order based on a single attribute:
# Get all users sorted by their name in descending order
@users = User.order(name: :desc)
Sort records based on multiple attributes:
# Get all users sorted by their age in ascending order and then by their name in descending order
@users = User.order(age: :asc, name: :desc)
Sort records based on an associated model:
# Get all posts sorted by the title of the associated author in ascending order
@posts = Post.includes(:author).order('authors.name ASC')

In this example, includes is used to eager-load the associated author model to avoid the N+1 query problem.

Sort records based on a custom SQL expression:
# Get all products sorted by the sum of their sales in descending order
@products = Product.order('SUM(sales) DESC')

In this example, a custom SQL expression is used to calculate the sum of sales for each product and sort the records based on the result.