diff --git a/lib/ransack/adapters/active_record/context.rb b/lib/ransack/adapters/active_record/context.rb index c55257b..8acf896 100644 --- a/lib/ransack/adapters/active_record/context.rb +++ b/lib/ransack/adapters/active_record/context.rb @@ -47,6 +47,10 @@ module Ransack scope_or_sort = scope_or_sort.direction == :asc ? Arel.sql("#{scope_or_sort.to_sql} NULLS FIRST") : Arel.sql("#{scope_or_sort.to_sql} NULLS LAST") when :nulls_last scope_or_sort = scope_or_sort.direction == :asc ? Arel.sql("#{scope_or_sort.to_sql} NULLS LAST") : Arel.sql("#{scope_or_sort.to_sql} NULLS FIRST") + when :nulls_always_first + scope_or_sort = Arel.sql("#{scope_or_sort.to_sql} NULLS FIRST") + when :nulls_always_last + scope_or_sort = Arel.sql("#{scope_or_sort.to_sql} NULLS LAST") end relation = relation.order(scope_or_sort) diff --git a/lib/ransack/configuration.rb b/lib/ransack/configuration.rb index 4347db5..1ca0434 100644 --- a/lib/ransack/configuration.rb +++ b/lib/ransack/configuration.rb @@ -149,7 +149,7 @@ module Ransack # User may want to configure it like this: # # Ransack.configure do |c| - # c.postgres_fields_sort_option = :nulls_first # or :nulls_last + # c.postgres_fields_sort_option = :nulls_first # or e.g. :nulls_always_last # end # # See this feature: https://www.postgresql.org/docs/13/queries-order.html diff --git a/spec/ransack/search_spec.rb b/spec/ransack/search_spec.rb index e66c2e5..99adb05 100644 --- a/spec/ransack/search_spec.rb +++ b/spec/ransack/search_spec.rb @@ -605,6 +605,18 @@ module Ransack s = Search.new(Person, s: 'doubled_name desc') expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" || \"people\".\"name\" DESC NULLS FIRST" + Ransack.configure { |c| c.postgres_fields_sort_option = :nulls_always_first } + s = Search.new(Person, s: 'doubled_name asc') + expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" || \"people\".\"name\" ASC NULLS FIRST" + s = Search.new(Person, s: 'doubled_name desc') + expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" || \"people\".\"name\" DESC NULLS FIRST" + + Ransack.configure { |c| c.postgres_fields_sort_option = :nulls_always_last } + s = Search.new(Person, s: 'doubled_name asc') + expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" || \"people\".\"name\" ASC NULLS LAST" + s = Search.new(Person, s: 'doubled_name desc') + expect(s.result.to_sql).to eq "SELECT \"people\".* FROM \"people\" ORDER BY \"people\".\"name\" || \"people\".\"name\" DESC NULLS LAST" + Ransack.options = default end end