Skip to content

Instantly share code, notes, and snippets.

@alpaca-tc
Created December 16, 2021 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alpaca-tc/b67df265f0aaf9d44cd565ca36d277d2 to your computer and use it in GitHub Desktop.
Save alpaca-tc/b67df265f0aaf9d44cd565ca36d277d2 to your computer and use it in GitHub Desktop.
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index d1b285101d..9ca4677c6f 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -352,9 +352,9 @@ def execute_grouped_calculation(operation, column_name, distinct) # :nodoc:
select_values.concat group_columns.map { |aliaz, field|
if field.respond_to?(:as)
- field.as(aliaz)
+ Arel::Nodes::As.new(field, Arel::Table.new(aliaz))
else
- "#{field} AS #{aliaz}"
+ Arel::Nodes::As.new(Arel::Nodes::SqlLiteral.new(field), Arel::Table.new(aliaz))
end
}
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index 428727733a..1812b037af 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -911,6 +911,13 @@ def test_group_by_with_quoted_count_and_order_by_alias
assert_equal expected, actual
end
+ def test_count_with_group_by_when_table_name_started_with_number
+ klass = Class.new(ActiveRecord::Base)
+ klass.table_name = '1_tables'
+ assert_equal({}, klass.group(:id).count)
+ assert_equal({}, klass.group('"1_tables"."id"').count)
+ end
+
def test_pluck_not_auto_table_name_prefix_if_column_included
Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
ids = Company.includes(:contracts).pluck(:developer_id)
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
index 471d89a3f8..a991af8981 100644
--- a/activerecord/test/schema/schema.rb
+++ b/activerecord/test/schema/schema.rb
@@ -1286,6 +1286,9 @@
t.integer :id
t.datetime :created_at
end
+
+ create_table :"1_tables", force: true do |t|
+ end
end
Course.connection.create_table :courses, force: true do |t|
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment