Skip to content

Commit 178b5da

Browse files
committed
Add more examples to #in_order_of [ci-skip]
Adds more examples to `#in_order_of`: - what happens when dealing with `enum` +columns+ - what happens when passing `nil` as a +value+ for nullable columns
1 parent f84b428 commit 178b5da

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

activerecord/lib/active_record/relation/query_methods.rb

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -606,7 +606,8 @@ def order!(*args) # :nodoc:
606606
self
607607
end
608608

609-
# Allows to specify an order by a specific set of values.
609+
# Allows to specify an <code>ORDER BY</code> clause to a query based on a given +column+,
610+
# ordered and filtered by the specific set of +values+.
610611
#
611612
# User.in_order_of(:id, [1, 5, 3])
612613
# # SELECT "users".* FROM "users"
@@ -617,6 +618,32 @@ def order!(*args) # :nodoc:
617618
# # WHEN "users"."id" = 3 THEN 3
618619
# # END ASC
619620
#
621+
# +column+ can point to an enum column; the actual query generated may be different depending
622+
# on the database adapter and the column definition.
623+
#
624+
# class Conversation < ActiveRecord::Base
625+
# enum :status, [ :active, :archived ]
626+
# end
627+
#
628+
# Conversation.in_order_of(:status, %w(archived active))
629+
# # SELECT "conversations".* FROM "conversations"
630+
# # WHERE "conversations"."status" IN (1, 0)
631+
# # ORDER BY CASE
632+
# # WHEN "conversations"."status" = 1 THEN 1
633+
# # WHEN "conversations"."status" = 0 THEN 2
634+
# # END ASC
635+
#
636+
# +values+ can also include +nil+.
637+
#
638+
# Conversation.in_order_of(:status, %w(nil archived active))
639+
# # SELECT "conversations".* FROM "conversations"
640+
# # WHERE ("conversations"."status" IN (1, 0) OR "conversations"."status" IS NULL)
641+
# # ORDER BY CASE
642+
# # WHEN "conversations"."status" IS NULL THEN 1
643+
# # WHEN "conversations"."status" = 1 THEN 2
644+
# # WHEN "conversations"."status" = 0 THEN 3
645+
# # END ASC
646+
#
620647
def in_order_of(column, values)
621648
klass.disallow_raw_sql!([column], permit: connection.column_name_with_order_matcher)
622649
return spawn.none! if values.empty?

0 commit comments

Comments
 (0)