@@ -10,20 +10,10 @@ def apply(relation)
1010 return order_by_association ( relation ) unless
1111 reflect_association ( relation ) . nil?
1212
13- order = relation . arel_table [ sorting_column ] . public_send ( direction )
13+ return order_by_column ( relation ) if
14+ column_exist? ( relation , sorting_column )
1415
15- tiebreak_key = relation . primary_key
16- tiebreak_order = relation . arel_table [ tiebreak_key ] . public_send ( direction )
17-
18- if column_exist? ( relation , sorting_column )
19- if column_exist? ( relation , tiebreak_key ) && sorting_column . to_s != tiebreak_key . to_s
20- relation . reorder ( order , tiebreak_order )
21- else
22- relation . reorder ( order )
23- end
24- else
25- relation
26- end
16+ relation
2717 end
2818
2919 def ordered_by? ( attr )
@@ -59,14 +49,22 @@ def opposite_direction
5949 ( direction == :asc ) ? :desc : :asc
6050 end
6151
52+ def order_by_column ( relation )
53+ order = relation . arel_table [ sorting_column ] . public_send ( direction )
54+ with_tiebreak (
55+ relation . reorder ( order ) ,
56+ ordered_column : sorting_column
57+ )
58+ end
59+
6260 def order_by_association ( relation )
6361 case relation_type ( relation )
6462 when :has_many
65- order_by_count ( relation )
63+ with_tiebreak ( order_by_count ( relation ) )
6664 when :belongs_to
67- order_by_belongs_to ( relation )
65+ with_tiebreak ( order_by_belongs_to ( relation ) )
6866 when :has_one
69- order_by_has_one ( relation )
67+ with_tiebreak ( order_by_has_one ( relation ) )
7068 else
7169 relation
7270 end
@@ -112,6 +110,25 @@ def column_exist?(table, column_name)
112110 table . columns_hash . key? ( column_name . to_s )
113111 end
114112
113+ def with_tiebreak ( relation , ordered_column : nil )
114+ tiebreak_key = relation . primary_key
115+ tiebreak_order = tiebreak_order_for ( relation )
116+
117+ if tiebreak_order && ordered_column . to_s != tiebreak_key . to_s
118+ relation . order ( tiebreak_order )
119+ else
120+ relation
121+ end
122+ end
123+
124+ def tiebreak_order_for ( relation )
125+ tiebreak_key = relation . primary_key
126+
127+ if tiebreak_key && column_exist? ( relation , tiebreak_key )
128+ relation . arel_table [ tiebreak_key ] . public_send ( direction )
129+ end
130+ end
131+
115132 def order_by_id_query ( relation )
116133 relation . arel_table [ association_foreign_key ( relation ) ] . public_send ( direction )
117134 end
0 commit comments