Ticket #9711: has_many_through_uniq_calculations.patch
| File has_many_through_uniq_calculations.patch, 2.9 kB (added by tarmo, 1 year ago) |
|---|
-
a/activerecord/lib/active_record/associations/has_many_through_association.rb
old new 103 103 loaded? ? @target.size : count 104 104 end 105 105 106 # Makes the calculation automatically distinct if the association 107 # is uniq. 108 def calculate(operation, *args, &block) 109 options = args.extract_options! 110 111 if @reflection.options[:uniq] && !options.has_key?(:distinct) 112 options[:distinct] = true 113 end 114 115 args << options 116 super(operation, *args, &block) 117 end 118 119 # Calculate average using SQL, not Enumerable 120 def average(*args, &block) 121 calculate(:avg, *args, &block) 122 end 123 106 124 # Calculate sum using SQL, not Enumerable 107 125 def sum(*args, &block) 108 126 calculate(:sum, *args, &block) -
a/activerecord/test/associations_test.rb
old new 402 402 403 403 class HasManyAssociationsTest < Test::Unit::TestCase 404 404 fixtures :accounts, :companies, :developers, :projects, 405 :developers_projects, :topics, :authors, :comments 405 :developers_projects, :topics, :authors, :comments, 406 :posts, :categories, :categorizations 406 407 407 408 def setup 408 409 Client.destroyed_client_ids.clear … … 1034 1035 def test_assign_ids_for_through 1035 1036 assert_raise(NoMethodError) { authors(:mary).comment_ids = [123] } 1036 1037 end 1038 1039 def test_sum_on_uniq_through_association_uses_distinct_automatically 1040 # non-unique posts.author_id: [ 1, 1 ] 1041 assert_equal 1, authors(:mary).unique_categorized_posts.sum('posts.author_id') 1042 assert_equal 2, authors(:mary).unique_categorized_posts.sum('posts.author_id', :distinct => false) 1043 end 1044 1045 def test_average_on_uniq_through_association_uses_distinct_automatically 1046 # non-unique posts.id: [2, 2] 1047 assert_equal 2, authors(:mary).unique_categorized_posts.average('posts.id') 1048 Categorization.create!( 1049 :author_id => authors(:mary).id, 1050 :post_id => posts(:thinking).id, 1051 :category_id => categories(:general).id) 1052 Categorization.create!( 1053 :author_id => authors(:mary).id, 1054 :post_id => posts(:welcome).id, 1055 :category_id => categories(:general).id) 1056 # non-unique posts.id: [1, 2, 2, 2] 1057 assert_equal 1.5, authors(:mary).unique_categorized_posts.average('posts.id') 1058 assert_equal 1.75, authors(:mary).unique_categorized_posts.average('posts.id', :distinct => false) 1059 end 1037 1060 end 1038 1061 1039 1062 class BelongsToAssociationsTest < Test::Unit::TestCase