allow ransack to treat nulls as always first or last

This commit is contained in:
mollerhoj 2021-05-19 12:19:22 +02:00
parent b627a386d7
commit 511894c35f
3 changed files with 17 additions and 1 deletions

View File

@ -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)

View File

@ -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

View File

@ -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