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

Changeset 7692

Show
Ignore:
Timestamp:
09/30/07 06:47:20 (2 years ago)
Author:
rick
Message:

Make size for has_many :through use counter cache if it exists. Closes #9734 [xaviershay]

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/activerecord/CHANGELOG

    r7690 r7692  
    11*2.0.0 [Preview Release]* (September 29th, 2007) [Includes duplicates of changes from 1.14.2 - 1.15.3] 
     2 
     3* Make size for has_many :through use counter cache if it exists.  Closes #9734 [xaviershay] 
    24 
    35* Remove DB2 adapter since IBM chooses to maintain their own adapter instead.  [Jeremy Kemper] 
  • trunk/activerecord/lib/active_record/associations/has_many_through_association.rb

    r7368 r7692  
    101101      # and you need to fetch that collection afterwards, it'll take one less SELECT query if you use length. 
    102102      def size 
    103         loaded? ? @target.size : count 
     103        return @owner.send(:read_attribute, cached_counter_attribute_name) if has_cached_counter? 
     104        return @target.size if loaded? 
     105        return count 
    104106      end 
    105107 
     
    259261 
    260262        alias_method :sql_conditions, :conditions 
     263 
     264        def has_cached_counter? 
     265          @owner.attribute_present?(cached_counter_attribute_name) 
     266        end 
     267 
     268        def cached_counter_attribute_name 
     269          "#{@reflection.name}_count" 
     270        end 
    261271    end 
    262272  end 
  • trunk/activerecord/test/associations/join_model_test.rb

    r7237 r7692  
    458458  end 
    459459 
     460  uses_mocha('has_many_through_collection_size_uses_counter_cache_if_it_exists') do 
     461    def test_has_many_through_collection_size_uses_counter_cache_if_it_exists 
     462      author = authors(:david) 
     463      author.stubs(:read_attribute).with('comments_count').returns(100) 
     464      assert_equal 100, author.comments.size 
     465      assert !author.comments.loaded? 
     466    end 
     467  end 
     468 
    460469  def test_adding_junk_to_has_many_through_should_raise_type_mismatch 
    461470    assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:thinking).tags << "Uhh what now?" }