Skip to content

Commit

Permalink
Improve Documentation around the options that can be passed to order.
Browse files Browse the repository at this point in the history
Co-authored-by: Petrik de Heus <petrik@deheus.net>
Co-authored-by: Jonathan Hefner <jonathan@hefner.pro>
  • Loading branch information
3 people committed Aug 19, 2021
1 parent dfef447 commit d6a38d2
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion activerecord/lib/active_record/relation/query_methods.rb
Expand Up @@ -354,17 +354,37 @@ def group!(*args) # :nodoc:
self
end

# Allows to specify an order attribute:
# Applies an <code>ORDER BY</code> clause to a query.
#
# #order accepts arguments in one of several formats.
#
# === symbols
#
# The symbol represents the name of the column you want to order the results by.
#
# User.order(:name)
# # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC
#
# By default, the order is ascending. If you want descending order, you can
# map the column name symbol to +:desc+.
#
# User.order(email: :desc)
# # SELECT "users".* FROM "users" ORDER BY "users"."email" DESC
#
# Multiple columns can be passed this way, and they will be applied in the order specified.
#
# User.order(:name, email: :desc)
# # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC
#
# === strings
#
# Strings are passed directly to the database, allowing you to specify
# simple SQL expressions.
#
# This could be a source of SQL injection, so only strings composed of plain
# column names and simple <code>function(column_name)</code> expressions
# with optional +ASC+/+DESC+ modifiers are allowed.
#
# User.order('name')
# # SELECT "users".* FROM "users" ORDER BY name
#
Expand All @@ -373,6 +393,19 @@ def group!(*args) # :nodoc:
#
# User.order('name DESC, email')
# # SELECT "users".* FROM "users" ORDER BY name DESC, email
#
# === Arel
#
# If you need to pass in complicated expressions that you have verified
# are safe for the DB, you can use Arel.
#
# User.order(Arel.sql('end_date - start_date'))
# # SELECT "users".* FROM "users" ORDER BY end_date - start_date
#
# Custom query syntax, like JSON columns for Postgres, is supported in this way.
#
# User.order(Arel.sql("payload->>'kind'"))
# # SELECT "users".* FROM "users" ORDER BY payload->>'kind'
def order(*args)
check_if_method_has_arguments!(__callee__, args) do
sanitize_order_arguments(args)
Expand Down

0 comments on commit d6a38d2

Please sign in to comment.