Skip to content

Commit

Permalink
Adding :from scoping to ActiveRecord calculations
Browse files Browse the repository at this point in the history
Signed-off-by: Michael Koziarski <michael@koziarski.com>
[#1229 state:committed]
  • Loading branch information
mrduncan authored and NZKoz committed Aug 9, 2009
1 parent 1f6afe4 commit 3b37985
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 0 deletions.
2 changes: 2 additions & 0 deletions activerecord/lib/active_record/calculations.rb
Expand Up @@ -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)} "
Expand Down
6 changes: 6 additions & 0 deletions activerecord/test/cases/calculations_test.rb
Expand Up @@ -2,6 +2,8 @@
require 'models/company'
require 'models/topic'
require 'models/edge'
require 'models/club'
require 'models/organization'

Company.has_many :accounts

Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions 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

0 comments on commit 3b37985

Please sign in to comment.