@@ -391,12 +391,36 @@ def apply_filters(records, filters, options)
391391 end
392392 end
393393
394+ def test_custom_sorting
395+ post_resource = PostResource . new ( Post . find ( 1 ) , nil )
396+ comment_ids = post_resource . comments . map { |c | c . _model . id }
397+ assert_equal [ 1 , 2 ] , comment_ids
398+
399+ # define apply_sort method on post resource that will never sort
400+ PostResource . instance_eval do
401+ def apply_sort ( records , criteria , context = { } )
402+ if criteria . key? ( 'name' )
403+ # this sort will never occure
404+ records . order ( 'name asc' )
405+ end
406+ end
407+ end
408+
409+ sorted_comment_ids = post_resource . comments ( sort_criteria : [ { field : 'id' , direction : :desc } ] ) . map { |c | c . _model . id }
410+ assert_equal [ 2 , 1 ] , sorted_comment_ids
411+ ensure
412+ # reset method to original implementation
413+ PostResource . instance_eval do
414+ undef :apply_sort
415+ end
416+ end
417+
394418 def test_to_many_relationship_sorts
395419 post_resource = PostResource . new ( Post . find ( 1 ) , nil )
396420 comment_ids = post_resource . comments . map { |c | c . _model . id }
397421 assert_equal [ 1 , 2 ] , comment_ids
398422
399- # define apply_filters method on post resource to sort descending
423+ # define apply_sort method on post resource to sort descending
400424 PostResource . instance_eval do
401425 def apply_sort ( records , criteria , context = { } )
402426 # :nocov:
@@ -412,28 +436,7 @@ def apply_sort(records, criteria, context = {})
412436 ensure
413437 # reset method to original implementation
414438 PostResource . instance_eval do
415- def apply_sort ( records , order_options , _context = { } )
416- # :nocov:
417- if order_options . any?
418- order_options . each_pair do |field , direction |
419- if field . to_s . include? ( "." )
420- *model_names , column_name = field . split ( "." )
421-
422- associations = _lookup_association_chain ( [ records . model . to_s , *model_names ] )
423- joins_query = _record_accessor . _build_joins ( [ records . model , *associations ] )
424-
425- # _sorting is appended to avoid name clashes with manual joins eg. overriden filters
426- order_by_query = "#{ associations . last . name } _sorting.#{ column_name } #{ direction } "
427- records = records . joins ( joins_query ) . order ( order_by_query )
428- else
429- records = records . order ( field => direction )
430- end
431- end
432- end
433-
434- records
435- # :nocov:
436- end
439+ undef :apply_sort
437440 end
438441 end
439442
0 commit comments