@@ -378,12 +378,36 @@ def apply_filters(records, filters, options)
378
378
end
379
379
end
380
380
381
+ def test_custom_sorting
382
+ post_resource = PostResource . new ( Post . find ( 1 ) , nil )
383
+ comment_ids = post_resource . comments . map { |c | c . _model . id }
384
+ assert_equal [ 1 , 2 ] , comment_ids
385
+
386
+ # define apply_sort method on post resource that will never sort
387
+ PostResource . instance_eval do
388
+ def apply_sort ( records , criteria , context = { } )
389
+ if criteria . key? ( 'name' )
390
+ # this sort will never occure
391
+ records . order ( 'name asc' )
392
+ end
393
+ end
394
+ end
395
+
396
+ sorted_comment_ids = post_resource . comments ( sort_criteria : [ { field : 'id' , direction : :desc } ] ) . map { |c | c . _model . id }
397
+ assert_equal [ 2 , 1 ] , sorted_comment_ids
398
+ ensure
399
+ # reset method to original implementation
400
+ PostResource . instance_eval do
401
+ undef :apply_sort
402
+ end
403
+ end
404
+
381
405
def test_to_many_relationship_sorts
382
406
post_resource = PostResource . new ( Post . find ( 1 ) , nil )
383
407
comment_ids = post_resource . comments . map { |c | c . _model . id }
384
408
assert_equal [ 1 , 2 ] , comment_ids
385
409
386
- # define apply_filters method on post resource to sort descending
410
+ # define apply_sort method on post resource to sort descending
387
411
PostResource . instance_eval do
388
412
def apply_sort ( records , criteria , context = { } )
389
413
# :nocov:
@@ -399,28 +423,7 @@ def apply_sort(records, criteria, context = {})
399
423
ensure
400
424
# reset method to original implementation
401
425
PostResource . instance_eval do
402
- def apply_sort ( records , order_options , _context = { } )
403
- # :nocov:
404
- if order_options . any?
405
- order_options . each_pair do |field , direction |
406
- if field . to_s . include? ( "." )
407
- *model_names , column_name = field . split ( "." )
408
-
409
- associations = _lookup_association_chain ( [ records . model . to_s , *model_names ] )
410
- joins_query = _record_accessor . _build_joins ( [ records . model , *associations ] )
411
-
412
- # _sorting is appended to avoid name clashes with manual joins eg. overriden filters
413
- order_by_query = "#{ associations . last . name } _sorting.#{ column_name } #{ direction } "
414
- records = records . joins ( joins_query ) . order ( order_by_query )
415
- else
416
- records = records . order ( field => direction )
417
- end
418
- end
419
- end
420
-
421
- records
422
- # :nocov:
423
- end
426
+ undef :apply_sort
424
427
end
425
428
end
426
429
0 commit comments