Skip to content

Commit 3b37985

Browse files
mrduncanNZKoz
authored andcommitted
Adding :from scoping to ActiveRecord calculations
Signed-off-by: Michael Koziarski <michael@koziarski.com> [#1229 state:committed]
1 parent 1f6afe4 commit 3b37985

File tree

3 files changed

+10
-0
lines changed

3 files changed

+10
-0
lines changed

activerecord/lib/active_record/calculations.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,8 @@ def construct_calculation_sql(operation, column_name, options) #:nodoc:
197197
sql << ", #{options[:group_field]} AS #{options[:group_alias]}" if options[:group]
198198
if options[:from]
199199
sql << " FROM #{options[:from]} "
200+
elsif scope && scope[:from]
201+
sql << " FROM #{scope[:from]} "
200202
else
201203
sql << " FROM (SELECT #{distinct}#{column_name}" if use_workaround
202204
sql << " FROM #{connection.quote_table_name(table_name)} "

activerecord/test/cases/calculations_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
require 'models/company'
33
require 'models/topic'
44
require 'models/edge'
5+
require 'models/club'
6+
require 'models/organization'
57

68
Company.has_many :accounts
79

@@ -223,6 +225,10 @@ def test_should_sum_scoped_field
223225
assert_equal 15, companies(:rails_core).companies.sum(:id)
224226
end
225227

228+
def test_should_sum_scoped_field_with_from
229+
assert_equal Club.count, Organization.clubs.count
230+
end
231+
226232
def test_should_sum_scoped_field_with_conditions
227233
assert_equal 8, companies(:rails_core).companies.sum(:id, :conditions => 'id > 7')
228234
end
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
class Organization < ActiveRecord::Base
22
has_many :member_details
33
has_many :members, :through => :member_details
4+
5+
named_scope :clubs, { :from => 'clubs' }
46
end

0 commit comments

Comments
 (0)