From e8d8f3d651d190fc187f520cfe25b0ce3ad0f0e3 Mon Sep 17 00:00:00 2001 From: Matt Duncan Date: Fri, 7 Aug 2009 22:55:19 -0400 Subject: [PATCH] Adding :from scoping to ActiveRecord calculations --- activerecord/lib/active_record/calculations.rb | 2 ++ activerecord/test/cases/calculations_test.rb | 6 ++++++ activerecord/test/models/organization.rb | 2 ++ 3 files changed, 10 insertions(+), 0 deletions(-) diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index 7af97d7..6eee401 100644 --- a/activerecord/lib/active_record/calculations.rb +++ b/activerecord/lib/active_record/calculations.rb @@ -190,6 +190,8 @@ module ActiveRecord 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 b4f76cb..f428052 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -5,6 +5,8 @@ require 'models/edge' require 'models/owner' require 'models/pet' require 'models/toy' +require 'models/club' +require 'models/organization' Company.has_many :accounts @@ -226,6 +228,10 @@ class CalculationsTest < ActiveRecord::TestCase 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 d79d503..c857261 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 -- 1.6.0