Skip to content

Commit 074c7f5

Browse files
Merge pull request rails#43018 from ChaelCodes/document-order
[DOCS] Improve Documentation for ActiveRecord's order Method [ci-skip]
2 parents 64a3bb8 + d6a38d2 commit 074c7f5

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

activerecord/lib/active_record/relation/query_methods.rb

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -354,17 +354,37 @@ def group!(*args) # :nodoc:
354354
self
355355
end
356356

357-
# Allows to specify an order attribute:
357+
# Applies an <code>ORDER BY</code> clause to a query.
358+
#
359+
# #order accepts arguments in one of several formats.
360+
#
361+
# === symbols
362+
#
363+
# The symbol represents the name of the column you want to order the results by.
358364
#
359365
# User.order(:name)
360366
# # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC
361367
#
368+
# By default, the order is ascending. If you want descending order, you can
369+
# map the column name symbol to +:desc+.
370+
#
362371
# User.order(email: :desc)
363372
# # SELECT "users".* FROM "users" ORDER BY "users"."email" DESC
364373
#
374+
# Multiple columns can be passed this way, and they will be applied in the order specified.
375+
#
365376
# User.order(:name, email: :desc)
366377
# # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC
367378
#
379+
# === strings
380+
#
381+
# Strings are passed directly to the database, allowing you to specify
382+
# simple SQL expressions.
383+
#
384+
# This could be a source of SQL injection, so only strings composed of plain
385+
# column names and simple <code>function(column_name)</code> expressions
386+
# with optional +ASC+/+DESC+ modifiers are allowed.
387+
#
368388
# User.order('name')
369389
# # SELECT "users".* FROM "users" ORDER BY name
370390
#
@@ -373,6 +393,19 @@ def group!(*args) # :nodoc:
373393
#
374394
# User.order('name DESC, email')
375395
# # SELECT "users".* FROM "users" ORDER BY name DESC, email
396+
#
397+
# === Arel
398+
#
399+
# If you need to pass in complicated expressions that you have verified
400+
# are safe for the DB, you can use Arel.
401+
#
402+
# User.order(Arel.sql('end_date - start_date'))
403+
# # SELECT "users".* FROM "users" ORDER BY end_date - start_date
404+
#
405+
# Custom query syntax, like JSON columns for Postgres, is supported in this way.
406+
#
407+
# User.order(Arel.sql("payload->>'kind'"))
408+
# # SELECT "users".* FROM "users" ORDER BY payload->>'kind'
376409
def order(*args)
377410
check_if_method_has_arguments!(__callee__, args) do
378411
sanitize_order_arguments(args)

0 commit comments

Comments
 (0)