Skip to content

Commit

Permalink
Merge r8778 from trunk: fix calculations on associations with custom …
Browse files Browse the repository at this point in the history
…:foreign_key. References rails#8117.

git-svn-id: http://svn-commit.rubyonrails.org/rails/branches/2-0-stable@8779 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information
jeremy committed Feb 2, 2008
1 parent f09a529 commit c31a04a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/calculations.rb
Expand Up @@ -213,7 +213,7 @@ def execute_grouped_calculation(operation, column_name, column, options) #:nodoc
group_attr = options[:group].to_s
association = reflect_on_association(group_attr.to_sym)
associated = association && association.macro == :belongs_to # only count belongs_to associations
group_field = (associated ? "#{options[:group]}_id" : options[:group]).to_s
group_field = associated ? association.primary_key_name : group_attr
group_alias = column_alias_for(group_field)
group_column = column_for group_field
sql = construct_calculation_sql(operation, column_name, options.merge(:group_field => group_field, :group_alias => group_alias))
Expand Down
10 changes: 9 additions & 1 deletion activerecord/test/calculations_test.rb
Expand Up @@ -159,7 +159,15 @@ def test_should_group_by_association_with_non_numeric_foreign_key
assert_equal 1, c.first.last
end
end


def test_should_calculate_grouped_association_with_foreign_key_option
Account.belongs_to :another_firm, :class_name => 'Firm', :foreign_key => 'firm_id'
c = Account.count(:all, :group => :another_firm)
assert_equal 1, c[companies(:first_firm)]
assert_equal 2, c[companies(:rails_core)]
assert_equal 1, c[companies(:first_client)]
end

def test_should_not_modify_options_when_using_includes
options = {:conditions => 'companies.id > 1', :include => :firm}
options_copy = options.dup
Expand Down

0 comments on commit c31a04a

Please sign in to comment.