diff --git a/lib/ransack/adapters/active_record/context.rb b/lib/ransack/adapters/active_record/context.rb index 3fbd8356a..c55257bbd 100644 --- a/lib/ransack/adapters/active_record/context.rb +++ b/lib/ransack/adapters/active_record/context.rb @@ -44,9 +44,9 @@ def evaluate(search, opts = {}) else case Ransack.options[:postgres_fields_sort_option] when :nulls_first - scope_or_sort = scope_or_sort.direction == :asc ? "#{scope_or_sort.to_sql} NULLS FIRST" : "#{scope_or_sort.to_sql} NULLS LAST" + 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 ? "#{scope_or_sort.to_sql} NULLS LAST" : "#{scope_or_sort.to_sql} NULLS FIRST" + 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") end relation = relation.order(scope_or_sort) diff --git a/spec/ransack/search_spec.rb b/spec/ransack/search_spec.rb index 72c54dd4f..15f47b6e0 100644 --- a/spec/ransack/search_spec.rb +++ b/spec/ransack/search_spec.rb @@ -554,6 +554,27 @@ def remove_quotes_and_backticks(str) Ransack.options = default end + + it "PG's sort option with double name", if: ::ActiveRecord::Base.connection.adapter_name == "PostgreSQL" do + default = Ransack.options.clone + + 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" + + Ransack.configure { |c| c.postgres_fields_sort_option = :nulls_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 LAST" + + Ransack.configure { |c| c.postgres_fields_sort_option = :nulls_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 FIRST" + + Ransack.options = default + end end describe '#method_missing' do