@@ -701,7 +701,16 @@ def order!(*args) # :nodoc:
701
701
# # WHEN "conversations"."status" = 0 THEN 3
702
702
# # END ASC
703
703
#
704
- def in_order_of ( column , values )
704
+ # +filter+ can be set to +false+ to include all results instead of only the ones specified in +values+.
705
+ #
706
+ # Conversation.in_order_of(:status, [:archived, :active], filter: false)
707
+ # # SELECT "conversations".* FROM "conversations"
708
+ # # ORDER BY CASE
709
+ # # WHEN "conversations"."status" = 1 THEN 1
710
+ # # WHEN "conversations"."status" = 0 THEN 2
711
+ # # ELSE 3
712
+ # # END ASC
713
+ def in_order_of ( column , values , filter : true )
705
714
model . disallow_raw_sql! ( [ column ] , permit : model . adapter_class . column_name_with_order_matcher )
706
715
return spawn . none! if values . empty?
707
716
@@ -711,16 +720,20 @@ def in_order_of(column, values)
711
720
values = values . map { |value | model . type_caster . type_cast_for_database ( column , value ) }
712
721
arel_column = column . is_a? ( Arel ::Nodes ::SqlLiteral ) ? column : order_column ( column . to_s )
713
722
714
- where_clause =
715
- if values . include? ( nil )
716
- arel_column . in ( values . compact ) . or ( arel_column . eq ( nil ) )
717
- else
718
- arel_column . in ( values )
719
- end
723
+ scope = spawn . order! ( build_case_for_value_position ( arel_column , values , filter : filter ) )
720
724
721
- spawn
722
- . order! ( build_case_for_value_position ( arel_column , values ) )
723
- . where! ( where_clause )
725
+ if filter
726
+ where_clause =
727
+ if values . include? ( nil )
728
+ arel_column . in ( values . compact ) . or ( arel_column . eq ( nil ) )
729
+ else
730
+ arel_column . in ( values )
731
+ end
732
+
733
+ scope = scope . where! ( where_clause )
734
+ end
735
+
736
+ scope
724
737
end
725
738
726
739
# Replaces any existing order defined on the relation with the specified order.
@@ -2091,12 +2104,13 @@ def order_column(field)
2091
2104
end
2092
2105
end
2093
2106
2094
- def build_case_for_value_position ( column , values )
2107
+ def build_case_for_value_position ( column , values , filter : true )
2095
2108
node = Arel ::Nodes ::Case . new
2096
2109
values . each . with_index ( 1 ) do |value , order |
2097
2110
node . when ( column . eq ( value ) ) . then ( order )
2098
2111
end
2099
2112
2113
+ node = node . else ( values . length + 1 ) unless filter
2100
2114
Arel ::Nodes ::Ascending . new ( node )
2101
2115
end
2102
2116
0 commit comments