Skip to content

Commit

Permalink
Add more examples to #in_order_of [ci-skip]
Browse files Browse the repository at this point in the history
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
  • Loading branch information
thdaraujo committed Jan 21, 2024
1 parent f84b428 commit 178b5da
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion activerecord/lib/active_record/relation/query_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,8 @@ def order!(*args) # :nodoc:
self
end

# Allows to specify an order by a specific set of values.
# Allows to specify an <code>ORDER BY</code> clause to a query based on a given +column+,
# ordered and filtered by the specific set of +values+.
#
# User.in_order_of(:id, [1, 5, 3])
# # SELECT "users".* FROM "users"
Expand All @@ -617,6 +618,32 @@ def order!(*args) # :nodoc:
# # WHEN "users"."id" = 3 THEN 3
# # END ASC
#
# +column+ can point to an enum column; the actual query generated may be different depending
# on the database adapter and the column definition.
#
# class Conversation < ActiveRecord::Base
# enum :status, [ :active, :archived ]
# end
#
# Conversation.in_order_of(:status, %w(archived active))
# # SELECT "conversations".* FROM "conversations"
# # WHERE "conversations"."status" IN (1, 0)
# # ORDER BY CASE
# # WHEN "conversations"."status" = 1 THEN 1
# # WHEN "conversations"."status" = 0 THEN 2
# # END ASC
#
# +values+ can also include +nil+.
#
# Conversation.in_order_of(:status, %w(nil archived active))
# # SELECT "conversations".* FROM "conversations"
# # WHERE ("conversations"."status" IN (1, 0) OR "conversations"."status" IS NULL)
# # ORDER BY CASE
# # WHEN "conversations"."status" IS NULL THEN 1
# # WHEN "conversations"."status" = 1 THEN 2
# # WHEN "conversations"."status" = 0 THEN 3
# # END ASC
#
def in_order_of(column, values)
klass.disallow_raw_sql!([column], permit: connection.column_name_with_order_matcher)
return spawn.none! if values.empty?
Expand Down

0 comments on commit 178b5da

Please sign in to comment.