@@ -354,17 +354,37 @@ def group!(*args) # :nodoc:
354
354
self
355
355
end
356
356
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.
358
364
#
359
365
# User.order(:name)
360
366
# # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC
361
367
#
368
+ # By default, the order is ascending. If you want descending order, you can
369
+ # map the column name symbol to +:desc+.
370
+ #
362
371
# User.order(email: :desc)
363
372
# # SELECT "users".* FROM "users" ORDER BY "users"."email" DESC
364
373
#
374
+ # Multiple columns can be passed this way, and they will be applied in the order specified.
375
+ #
365
376
# User.order(:name, email: :desc)
366
377
# # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC
367
378
#
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
+ #
368
388
# User.order('name')
369
389
# # SELECT "users".* FROM "users" ORDER BY name
370
390
#
@@ -373,6 +393,19 @@ def group!(*args) # :nodoc:
373
393
#
374
394
# User.order('name DESC, email')
375
395
# # 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'
376
409
def order ( *args )
377
410
check_if_method_has_arguments! ( __callee__ , args ) do
378
411
sanitize_order_arguments ( args )
0 commit comments