Skip to content

Commit 533a9f8

Browse files
committed
Merge pull request rails#3507 from jmazzi/issue-3503
Preserve SELECT columns on the COUNT for finder_sql when possible
1 parent b5f908a commit 533a9f8

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

activerecord/lib/active_record/associations/collection_association.rb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -344,8 +344,12 @@ def custom_counter_sql
344344
if options[:counter_sql]
345345
interpolate(options[:counter_sql])
346346
else
347-
# replace the SELECT clause with COUNT(*), preserving any hints within /* ... */
348-
interpolate(options[:finder_sql]).sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{$1}COUNT(*) FROM" }
347+
# replace the SELECT clause with COUNT(SELECTS), preserving any hints within /* ... */
348+
interpolate(options[:finder_sql]).sub(/SELECT\b(\/\*.*?\*\/ )?(.*)\bFROM\b/im) do
349+
count_with = $2.to_s
350+
count_with = '*' if count_with.blank? || count_with =~ /,/
351+
"SELECT #{$1}COUNT(#{count_with}) FROM"
352+
end
349353
end
350354
end
351355

activerecord/test/cases/associations/has_many_associations_test.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,21 @@ def test_should_fail
4141
end
4242
end
4343

44+
class HasManyAssociationsTestForCountDistinctWithFinderSql < ActiveRecord::TestCase
45+
class Invoice < ActiveRecord::Base
46+
has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT DISTINCT line_items.amount from line_items"
47+
end
48+
49+
def test_should_count_distinct_results
50+
invoice = Invoice.new
51+
invoice.custom_line_items << LineItem.new(:amount => 0)
52+
invoice.custom_line_items << LineItem.new(:amount => 0)
53+
invoice.save!
54+
55+
assert_equal 1, invoice.custom_line_items.count
56+
end
57+
end
58+
4459

4560

4661
class HasManyAssociationsTest < ActiveRecord::TestCase

0 commit comments

Comments
 (0)