Skip to content

Commit

Permalink
Ensure calculations respect scoped :select [#1334 state:resolved]
Browse files Browse the repository at this point in the history
Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information
stopdropandrew authored and lifo committed Mar 7, 2009
1 parent ccb0a92 commit 6543426
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
18 changes: 13 additions & 5 deletions activerecord/lib/active_record/calculations.rb
Expand Up @@ -141,22 +141,30 @@ def calculate(operation, column_name, options = {})
def construct_count_options_from_args(*args)
options = {}
column_name = :all

# We need to handle
# count()
# count(:column_name=:all)
# count(options={})
# count(column_name=:all, options={})
# selects specified by scopes
case args.size
when 0
column_name = scope(:find)[:select] if scope(:find)
when 1
args[0].is_a?(Hash) ? options = args[0] : column_name = args[0]
if args[0].is_a?(Hash)
column_name = scope(:find)[:select] if scope(:find)
options = args[0]
else
column_name = args[0]
end
when 2
column_name, options = args
else
raise ArgumentError, "Unexpected parameters passed to count(): #{args.inspect}"
end if args.size > 0
[column_name, options]
end

[column_name || :all, options]
end

def construct_calculation_sql(operation, column_name, options) #:nodoc:
Expand Down
11 changes: 11 additions & 0 deletions activerecord/test/cases/calculations_test.rb
Expand Up @@ -264,6 +264,17 @@ def test_should_count_selected_field_with_include
assert_equal 4, Account.count(:distinct => true, :include => :firm, :select => :credit_limit)
end

def test_should_count_scoped_select
Account.update_all("credit_limit = 50")
assert_equal 1, Account.scoped(:select => "DISTINCT credit_limit").count
end

def test_should_count_scoped_select_with_options
Account.update_all("credit_limit = 50")
Account.first.update_attribute('credit_limit', 49)
assert_equal 1, Account.scoped(:select => "DISTINCT credit_limit").count(:conditions => [ 'credit_limit >= 50'] )
end

def test_should_count_manual_select_with_include
assert_equal 6, Account.count(:select => "DISTINCT accounts.id", :include => :firm)
end
Expand Down

0 comments on commit 6543426

Please sign in to comment.