Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #8801: has_many_through_uniq_count.patch

File has_many_through_uniq_count.patch, 2.1 kB (added by lifofifo, 1 year ago)

Updated against latest edge

  • activerecord/test/associations/join_model_test.rb

    old new  
    3030    assert_equal 2, authors(:mary).categorized_posts.size 
    3131    assert_equal 1, authors(:mary).unique_categorized_posts.size 
    3232  end 
    33  
     33   
     34  def test_has_many_uniq_through_count 
     35    author = authors(:mary) 
     36    assert !authors(:mary).unique_categorized_posts.loaded? 
     37    assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count } 
     38    assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count(:title) } 
     39    assert_queries(1) { assert_equal 0, author.unique_categorized_posts.count(:title, :conditions => "title is NULL") } 
     40    assert !authors(:mary).unique_categorized_posts.loaded? 
     41  end 
     42   
    3443  def test_polymorphic_has_many 
    3544    assert posts(:welcome).taggings.include?(taggings(:welcome_general)) 
    3645  end 
  • activerecord/lib/active_record/associations/has_many_through_association.rb

    old new  
    100100      def sum(*args, &block) 
    101101        calculate(:sum, *args, &block) 
    102102      end 
     103       
     104      def count(*args) 
     105        column_name, options = @reflection.klass.send(:construct_count_options_from_args, *args) 
     106        if @reflection.options[:uniq] 
     107          # This is needed becase 'SELECT count(DISTINCT *)..' is not valid sql statement. 
     108          column_name = "#{@reflection.klass.table_name}.#{@reflection.klass.primary_key}" if column_name == :all 
     109          options.merge!(:distinct => true)  
     110        end 
     111        @reflection.klass.send(:with_scope, construct_scope) { @reflection.klass.count(column_name, options) }  
     112      end 
    103113 
    104114      protected 
    105115        def method_missing(method, *args, &block)