diff options
author | Sean Griffin <sean@thoughtbot.com> | 2014-11-01 17:15:12 -0600 |
---|---|---|
committer | Sean Griffin <sean@thoughtbot.com> | 2014-11-01 17:15:55 -0600 |
commit | daab7e59a6196fa2bbab17dc4a88b095a211fc96 (patch) | |
tree | bc25e4adfed18572b619c5051c6e784bfe5c5551 | |
parent | 5e745dc3e225274c8eb0ae106ac827e0fcf6b92b (diff) | |
download | rails-daab7e59a6196fa2bbab17dc4a88b095a211fc96.tar.gz rails-daab7e59a6196fa2bbab17dc4a88b095a211fc96.tar.bz2 rails-daab7e59a6196fa2bbab17dc4a88b095a211fc96.zip |
Correctly cast calculation results on PG
MySQL reports the column name as `"MAX(developer_id)"`. PG will report
it as `"max"`
4 files changed, 17 insertions, 2 deletions
@@ -14,7 +14,7 @@ gem 'rack-cache', '~> 1.2' gem 'jquery-rails', '~> 4.0.0.beta2' gem 'coffee-rails', '~> 4.1.0' gem 'turbolinks' -gem 'arel', '~> 6.0.0.beta2' +gem 'arel', github: 'rails/arel' # require: false so bcrypt is loaded only when has_secure_password is used. # This is to avoid ActiveModel (and by extension the entire framework) diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index 96b7313234..dc1f3c9457 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -386,6 +386,10 @@ module ActiveRecord type_map.lookup(sql_type) end + def column_name_for_operation(operation, node) # :nodoc: + node.to_sql + end + protected def initialize_type_map(m) # :nodoc: diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 8e209e1051..e472741660 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -393,6 +393,16 @@ module ActiveRecord super(oid) end + def column_name_for_operation(operation, node) # :nodoc: + OPERATION_ALIASES.fetch(operation) { operation.downcase } + end + + OPERATION_ALIASES = { # :nodoc: + "maximum" => "max", + "minimum" => "min", + "average" => "avg", + } + protected # Returns the version of the connected PostgreSQL server. diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index e20cc0e76d..c8ebb41131 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -253,7 +253,8 @@ module ActiveRecord select_value = operation_over_aggregate_column(column, operation, distinct) - column_alias = select_value.alias || select_value.to_sql + column_alias = select_value.alias + column_alias ||= @klass.connection.column_name_for_operation(operation, select_value) relation.select_values = [select_value] query_builder = relation.arel |