From ab0277f22005b9690393318ef9adf94d815c1611 Mon Sep 17 00:00:00 2001 From: Rick Olson Date: Mon, 31 Jul 2006 21:06:19 +0000 Subject: Calculate sum with SQL, not Enumerable on HasManyThrough Associations. [Dan Peterson] git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@4640 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- activerecord/CHANGELOG | 2 ++ .../lib/active_record/associations/has_many_through_association.rb | 7 ++++++- activerecord/test/associations_join_model_test.rb | 4 ++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index 7900524a74..389de82445 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* Calculate sum with SQL, not Enumerable on HasManyThrough Associations. [Dan Peterson] + * Factor the attribute#{suffix} methods out of method_missing for easier extension. [Jeremy Kemper] * Patch sql injection vulnerability when using integer or float columns. [Jamis Buck] diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index c352a009d6..8f4ac104ad 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -47,7 +47,12 @@ module ActiveRecord [:push, :concat, :create, :build].each do |method| alias_method method, :<< end - + + # Calculate sum using SQL, not Enumerable + def sum(*args, &block) + calculate(:sum, *args, &block) + end + protected def method_missing(method, *args, &block) if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method)) diff --git a/activerecord/test/associations_join_model_test.rb b/activerecord/test/associations_join_model_test.rb index ede21785e7..b5d48db8bc 100644 --- a/activerecord/test/associations_join_model_test.rb +++ b/activerecord/test/associations_join_model_test.rb @@ -370,6 +370,10 @@ class AssociationsJoinModelTest < Test::Unit::TestCase assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags.build(:name => 'foo') } assert_raise(ActiveRecord::ReadOnlyAssociation) { posts(:thinking).tags.create(:name => 'foo') } end + + def test_has_many_through_sum_uses_calculations + assert_nothing_raised { authors(:david).comments.sum(:post_id) } + end private # create dynamic Post models to allow different dependency options -- cgit v1.2.3