diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index 727f4c1dc620a636713a8db4e89e85a61be59148..4a88c43dfff640b980068a15bcbfa811edda8f20 100644 --- a/activerecord/lib/active_record/calculations.rb +++ b/activerecord/lib/active_record/calculations.rb @@ -197,6 +197,8 @@ def construct_calculation_sql(operation, column_name, options) #:nodoc: sql << ", #{options[:group_field]} AS #{options[:group_alias]}" if options[:group] if options[:from] sql << " FROM #{options[:from]} " + elsif scope && scope[:from] + sql << " FROM #{scope[:from]} " else sql << " FROM (SELECT #{distinct}#{column_name}" if use_workaround sql << " FROM #{connection.quote_table_name(table_name)} " diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 24bc4f71ce41287dfb38de2c05cf229a6859a537..c2e02763f617ff13a553a6884c91d99157837987 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -2,6 +2,8 @@ require 'models/company' require 'models/topic' require 'models/edge' +require 'models/club' +require 'models/organization' Company.has_many :accounts @@ -223,6 +225,10 @@ def test_should_sum_scoped_field assert_equal 15, companies(:rails_core).companies.sum(:id) end + def test_should_sum_scoped_field_with_from + assert_equal Club.count, Organization.clubs.count + end + def test_should_sum_scoped_field_with_conditions assert_equal 8, companies(:rails_core).companies.sum(:id, :conditions => 'id > 7') end diff --git a/activerecord/test/models/organization.rb b/activerecord/test/models/organization.rb index d79d5037c805320e19ef64b4575157f9571356b1..c85726169eeabba68728b5c770ca26559aa2d632 100644 --- a/activerecord/test/models/organization.rb +++ b/activerecord/test/models/organization.rb @@ -1,4 +1,6 @@ class Organization < ActiveRecord::Base has_many :member_details has_many :members, :through => :member_details + + named_scope :clubs, { :from => 'clubs' } end \ No newline at end of file